unit Auth.Server.Module;

interface

uses
  System.SysUtils, System.Classes, System.Generics.Collections,
  Aurelius.Comp.Connection,
  Aurelius.Drivers.Interfaces,
  XData.Aurelius.ConnectionPool, XData.Server.Module, XData.Comp.ConnectionPool,
  Sparkle.Comp.Server, Sparkle.Comp.JwtMiddleware, XData.Comp.Server,
  Sparkle.Comp.HttpSysDispatcher, Sparkle.Comp.CompressMiddleware,
  Sparkle.Comp.CorsMiddleware, Sparkle.HttpServer.Module,
  Sparkle.HttpServer.Context, Sparkle.Comp.GenericMiddleware,
  Sparkle.Comp.BasicAuthMiddleware;

type
  TAuthServerModule = class(TDataModule)
    SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher;
    XDataServer: TXDataServer;
    XDataServerLogging: TSparkleGenericMiddleware;
    XDataServerCORS: TSparkleCorsMiddleware;
    XDataServerCompress: TSparkleCompressMiddleware;
    XDataServerBasicauth: TSparkleBasicAuthMiddleware;
    procedure XDataServerLoggingMiddlewareCreate(Sender: TObject;
      var Middleware: IHttpServerMiddleware);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure StartAuthServer(ABaseUrl: string; AModelName: string);
  end;

const
  SERVER_PATH_SEGMENT = 'auth';

var
  AuthServerModule: TAuthServerModule;

implementation

uses
  Sparkle.Middleware.Cors,
  Sparkle.Middleware.Compress,
  XData.OpenApi.Service,
  Common.Logging,
  Common.Middleware.Logging;

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

{ TAuthServerModule }

procedure TAuthServerModule.StartAuthServer(ABaseUrl: string;
  AModelName: string);
var
  Url: string;
begin
  RegisterOpenApiService;

  Url := ABaseUrl;
  if not Url.EndsWith('/') then
    Url := Url + '/';
  Url := Url + SERVER_PATH_SEGMENT;

  XDataServer.BaseUrl := Url;
  XDataServer.ModelName := AModelName;

  SparkleHttpSysDispatcher.Start;
  Logger.Log(1, Format('Auth server module listening at "%s"', [Url]));
end;

procedure TAuthServerModule.XDataServerLoggingMiddlewareCreate(Sender: TObject;
  var Middleware: IHttpServerMiddleware);
begin
  Middleware := TLoggingMiddleware.Create(Logger);
end;

end.
