unit Common.Middleware.RejectAnonymousAccess;

interface

uses
  System.SysUtils,
  Sparkle.HttpServer.Module,
  Sparkle.HttpServer.Context,
  XData.Module.Base;

type
  TRejectAnonymousAccessMiddleware = class(THttpServerMiddleware, IHttpServerMiddleware)
  private
    procedure UnauthorizedAnswer(Resp: THttpServerResponse; const Msg: string);
  protected
    procedure ProcessRequest(Context: THttpServerContext; Next: THttpServerProc); override;
  end;

implementation

{ TRejectAnonymousAccessMiddleware }

procedure TRejectAnonymousAccessMiddleware.ProcessRequest(
  Context: THttpServerContext; Next: THttpServerProc);
begin
  if Context.Request.MethodType = THttpMethod.Options then
  begin
    Next(Context);
    Exit;
  end;

  if Context.Request.User = nil then
  begin
    UnauthorizedAnswer(Context.Response, 'Unauthorized ');
    Exit;
  end;

  Next(Context);
end;

procedure TRejectAnonymousAccessMiddleware.UnauthorizedAnswer(
  Resp: THttpServerResponse; const Msg: string);
begin
  Resp.StatusCode := 401;
  if Msg <> '' then
  begin
    Resp.ContentType := 'text/plain';
    Resp.Headers.SetValue(Header_AccessControlAllowOrigin, '*');
    Resp.Close(TEncoding.UTF8.GetBytes(Msg));
  end;
end;

end.
