unit Auth.Service.Login;

interface

uses
  XData.Service.Common,
  Auth.Service.Interfaces;

type
  [ServiceImplementation]
  TLoginService = class(TInterfacedObject, ILoginService)
  public
    function Login(const User, Password: string): string;
  end;

implementation

uses
  System.SysUtils,
  System.DateUtils,
  Bcl.JOSE.Core.Builder,
  Bcl.JOSE.Core.JWT,
  Aurelius.Global.Utils,
  XData.Sys.Exceptions,
  Common.Config;

{ TLoginService }

function TLoginService.Login(const User, Password: string): string;
var
  JWT: TJWT;
begin
  if User.Equals('admin') then
  begin
    if not Password.Equals(ServerConfig.AdminPassword) then
      raise EXDataHttpUnauthorized.Create('Invalid user or password')
  end
  else
    if User <> Password then
      raise EXDataHttpUnauthorized.Create('Invalid user or password');

  JWT := TJWT.Create;
  try
    Jwt.Claims.JWTId := LowerCase(Copy(TUtils.GuidToVariant(TUtils.NewGuid), 2, 36));
    Jwt.Claims.IssuedAt := Now;
    Jwt.Claims.Expiration := IncHour(Now, 24);
    JWT.Claims.SetClaimOfType<string>('user', User);
    JWT.Claims.SetClaimOfType<boolean>('admin', User = 'admin');
    Result := TJOSE.SHA256CompactToken(ServerConfig.JwtTokenSecret, JWT);
  finally
    JWT.Free;
  end;
end;

initialization
  RegisterServiceType(TLoginService);
end.
