unit dmServerContainer;

interface

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

type
  TServerContainer = class(TDataModule)
    SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher;
    XDataServer: TXDataServer;
    XDataServerBasicauth: TSparkleBasicAuthMiddleware;
    XDataServerGeneric: TSparkleGenericMiddleware;
    procedure XDataServerBasicauthAuthenticate(Sender: TObject; const UserName,
      Password: string; var User: IUserIdentity);
    procedure XDataServerGenericRequest(Sender: TObject;
      Context: THttpServerContext; Next: THttpServerProc);
  end;

var
  ServerContainer: TServerContainer;

implementation

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

procedure TServerContainer.XDataServerBasicauthAuthenticate(Sender: TObject;
  const UserName, Password: string; var User: IUserIdentity);
begin
  if (UserName = 'admin') and (Password = 'password') then
  begin
    User := TUserIdentity.Create;
    User.Claims.AddOrSet('username', UserName);
    User.Claims.AddOrSet('roles', 'admin'); // arbitrary info you might want to add
  end;
end;

procedure TServerContainer.XDataServerGenericRequest(Sender: TObject;
  Context: THttpServerContext; Next: THttpServerProc);
begin
  // do not allow anonymous requests
  if Context.Request.User = nil then
    Context.Response.StatusCode := 401
  else
    Next(Context);
end;

end.
