#1 2024-07-12 08:44:52

Flashcqxg
Member
Registered: 2018-01-11
Posts: 31

Does mORMot2 have middleware similar to TMS Sparkle

TMS Sparkle provides classes that allow you to create middleware interfaces and add them to the request processing pipeline. In other words, you can add custom functionality that preprocess the request before it's effectively processed by the main server module, and postprocess the response provided by it.
Does mORMot2 have middleware similar to this?

Offline

#2 2024-07-12 09:55:47

Coldzer0
Member
From: ::1
Registered: 2018-08-31
Posts: 35
Website

Re: Does mORMot2 have middleware similar to TMS Sparkle

In my projects, I'm using OnBeforeBody. It's a good point to check for API tokens or header values.

For example, I've had this in one of my projects.

function TMainServer.BeforeBody(var aUrl, aMethod, aInHeaders, aInContentType, aRemoteIP, aBearerToken: RawUtf8; aContentLength: Int64; aFlags: THttpServerRequestFlags): cardinal;
var
  AuthData : String;
Begin
  // Always return HTTP_UNAUTHORIZED if there's any problem ^_^
  Result := HTTP_UNAUTHORIZED;

  // If user asks for time/ping we allow it
  if (LowerCase(aUrl) = '/api/v1/time') or (LowerCase(aUrl) = '/api/v1/ping') Then
  begin
    Exit(HTTP_SUCCESS);
  end;

  if aBearerToken <> '' then
  begin
    AuthData := Base64ToBin(aBearerToken);
    // Check Telegram webapp initData
    if IsValidTelegramUser(AuthData) then
    begin
      if IsAllowedUser(GetUserIDFromToken(AuthData)) then
        Result := HTTP_SUCCESS;
    end;
  end;
End;

Mac, Windows, Linux
FPC Trunk, Lazarus Trunk, Delphi 12.x Latest

Offline

#3 2024-07-12 10:15:10

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,661
Website

Re: Does mORMot2 have middleware similar to TMS Sparkle

You have indeed several callbacks, at several levels.

At HTTP/HTTPS level, you have THttpServerGeneric 's OnBeforeBody, OnBeforeRequest, OnAfterRequest, OnAfterResponse callbacks.

At REST level, you have TRestServer 's OnStartUri, OnBeforeUri, OnAfterUri, OnErrorUri, OnIdle callbacks.

Note that in mORMot, you can have REST process without any HTTP involved, e.g. over WebSockets, or from a dll, or directly within the server process.
So for the business logic, you may use TRestServer callbacks.
And for the transport/representation logic, you may use THttpServerGeneric callbacks.

Offline

#4 2024-07-13 00:06:56

Flashcqxg
Member
Registered: 2018-01-11
Posts: 31

Re: Does mORMot2 have middleware similar to TMS Sparkle

thanks.

Offline

Board footer

Powered by FluxBB