unit ApiServerModule;

interface

uses
  System.SysUtils, System.Classes, Aurelius.Drivers.SQLite,
  Aurelius.Comp.Connection,
  Aurelius.Drivers.Interfaces,
  XData.Aurelius.ConnectionPool, XData.Server.Module, Sparkle.Comp.Server,
  XData.Comp.Server, XData.Comp.ConnectionPool, Sparkle.Comp.HttpSysDispatcher,
  Sparkle.Comp.JwtMiddleware, Sparkle.Middleware.Jwt, Aurelius.Criteria.Linq,
  Sparkle.HttpServer.Module, Sparkle.HttpServer.Context;

type
  TServerModule = class(TDataModule)
    AureliusConnection1: TAureliusConnection;
    SparkleHttpSysDispatcher1: TSparkleHttpSysDispatcher;
    XDataConnectionPool1: TXDataConnectionPool;
    XDataServer1: TXDataServer;
    XDataServer1JWT: TSparkleJwtMiddleware;
    procedure DataModuleCreate(Sender: TObject);
    procedure XDataServer1EntityList(Sender: TObject; Args: TEntityListArgs);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure StartServer;
    procedure StopServer;
  end;

var
  ServerModule: TServerModule;

implementation

uses
  DatabaseUtils;

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

procedure TServerModule.DataModuleCreate(Sender: TObject);
var
  Conn: IDBConnection;
begin
  AureliusConnection1.Params.Values['Database'] := ParamStr(0) + '.db';
  Conn := AureliusConnection1.CreateConnection;
  DatabaseUtils.UpdateDatabase(Conn);
end;

procedure TServerModule.StartServer;
begin
  SparkleHttpSysDispatcher1.Start;
end;

procedure TServerModule.StopServer;
begin
  SparkleHttpSysDispatcher1.Stop;
end;

procedure TServerModule.XDataServer1EntityList(Sender: TObject;
  Args: TEntityListArgs);
var
  User: IUserIdentity;
  IsAdmin: Boolean;
begin
  User := Args.Handler.Request.User;
  IsAdmin := (User <> nil) and User.Claims.Exists('admin') and User.Claims['admin'].AsBoolean;

  // Non-admin cannot see Nirvana
  if not IsAdmin and SameText(Args.Criteria.Clazz.ClassName, 'TArtist') then
    Args.Criteria.Add(not Linq['Name'].Contains('Nirvana'));
end;

end.
