unit Sparkle.Comp.BasicAuthMiddleware;

interface

uses
  System.Classes,
  Sparkle.Comp.Server,
  Sparkle.Security,
  Sparkle.HttpServer.Module,
  Sparkle.Middleware.BasicAuth;

type
  IUserIdentity = Sparkle.Security.IUserIdentity;
  TUserIdentity = Sparkle.Security.TUserIdentity;
  TBasicAuthAuthenticateEvent = procedure(Sender: TObject;
    const UserName, Password: string; var User: IUserIdentity) of object;

  TSparkleBasicAuthMiddleware = class(TSparkleMiddleware)
  private
    FRealm: string;
    FOnAuthenticate: TBasicAuthAuthenticateEvent;
  protected
    function CreateMiddlewareInterface: IHttpServerMiddleware; override;
    class function GetDisplayName: string; override;
    procedure DoAuthenticate(const UserName, Password: string;
      var User: IUserIdentity); virtual;
  public
    constructor Create(AOwner: TComponent); override;
  published
    property Realm: string read FRealm write FRealm;
    property OnAuthenticate: TBasicAuthAuthenticateEvent read FOnAuthenticate write FOnAuthenticate;
  end;

implementation

{ TSparkleBasicAuthMiddleware }

constructor TSparkleBasicAuthMiddleware.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Realm := 'TMS Sparkle Server';
end;

class function TSparkleBasicAuthMiddleware.GetDisplayName: string;
begin
  Result := 'Basic auth';
end;

procedure TSparkleBasicAuthMiddleware.DoAuthenticate(const UserName,
  Password: string; var User: IUserIdentity);
begin
  if Assigned(FOnAuthenticate) then
    FOnAuthenticate(Self, UserName, Password, User);
end;

function TSparkleBasicAuthMiddleware.CreateMiddlewareInterface: IHttpServerMiddleware;
begin
  Result := TBasicAuthMiddleware.Create(DoAuthenticate, Realm);
end;

end.
