unit Sparkle.Comp.JwtMiddleware;

{$I sparkle.inc}

interface

{$IFDEF DELPHIXE6_LVL}

uses
  System.Classes, System.SysUtils,
  Sparkle.Comp.Server,
  Sparkle.HttpServer.Module,
  Sparkle.Middleware.Jwt;

type
  TGetSecretEvent = procedure(Sender: TObject; var Secret: string) of object;

  TSparkleJwtMiddleware = class(TSparkleMiddleware)
  private
    FSecret: string;
    FAllowExpiredToken: Boolean;
    FForbidAnonymousAccess: Boolean;
    FOnGetSecret: TGetSecretEvent;
    function GetSecret: string;
  protected
    function CreateMiddlewareInterface: IHttpServerMiddleware; override;
    class function GetDisplayName: string; override;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property Secret: string read FSecret write FSecret;
    property ForbidAnonymousAccess: Boolean read FForbidAnonymousAccess write FForbidAnonymousAccess default False;
    property AllowExpiredToken: Boolean read FAllowExpiredToken write FAllowExpiredToken default False;
    property OnGetSecret: TGetSecretEvent read FOnGetSecret write FOnGetSecret;
  end;

{$ENDIF}

implementation

{$IFDEF DELPHIXE6_LVL}

{ TSparkleJwtMiddleware }

constructor TSparkleJwtMiddleware.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
end;

function TSparkleJwtMiddleware.CreateMiddlewareInterface: IHttpServerMiddleware;
begin
  Result := TJwtMiddleware.Create(GetSecret, ForbidAnonymousAccess, AllowExpiredToken);
end;

class function TSparkleJwtMiddleware.GetDisplayName: string;
begin
  Result := 'JWT';
end;

function TSparkleJwtMiddleware.GetSecret: string;
begin
  Result := Self.Secret;
  if Assigned(FOnGetSecret) then
    FOnGetSecret(Self, Result);

  if Result = '' then
    raise Exception.Create('TSparkleJwtMiddleware: Secret not specified');
end;

{$ENDIF}

end.
