unit Auth.Database;

interface

uses
  System.SysUtils, System.Classes, MemDS,
  Data.DB, DBAccess, Uni, UniProvider, PostgreSQLUniProvider;

type
  TAuthDatabase = class(TDataModule)
    uqMisc: TUniQuery;
    ucLemsOCSO: TUniConnection;
    uqUserPref: TUniQuery;
    uqAuth: TUniQuery;
    PostgreSQLUniProvider1: TPostgreSQLUniProvider;
    procedure DataModuleCreate(Sender: TObject);
    procedure DataModuleDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure SetLoginAuditEntry( userStr: string );
  end;

var
  AuthDatabase: TAuthDatabase;

implementation

uses
  System.JSON,
  Common.Config,
  Common.Logging,
  Common.Ini,
  uLibrary;

{%CLASSGROUP 'Vcl.Controls.TControl'}

{$R *.dfm}

procedure TAuthDatabase.DataModuleCreate(Sender: TObject);
begin
  ucLemsOCSO.ProviderName := 'PostgreSQL';
  ucLemsOCSO.Server := IniEntries.DatabaseServer;
  ucLemsOCSO.Port := IniEntries.DatabasePort;
  ucLemsOCSO.Database := IniEntries.DatabaseName;
  ucLemsOCSO.Username := IniEntries.DatabaseUsername;
  ucLemsOCSO.Password := IniEntries.DatabasePassword;
  ucLemsOCSO.LoginPrompt := False;

  try
    Logger.Log(2, '');
    Logger.Log(2, 'Connecting to PostgreSQL auth database...');
    if not ucLemsOCSO.Connected then
      ucLemsOCSO.Connect;
  except
    on E: Exception do
    begin
      Logger.Log(2, Format('Failed to connect to auth database: %s', [E.Message]));
      raise;
    end;
  end;
end;


procedure TAuthDatabase.DataModuleDestroy(Sender: TObject);
begin
  if ucLemsOCSO.Connected then
    ucLemsOCSO.Disconnect;
end;

procedure TAuthDatabase.SetLoginAuditEntry( userStr: string );
var
  auditMasterId: string;
  userInfo: TStringList;
  username: string;
  fullname: string;
  agency: string;
  userid: string;
  personnelid: string;
begin
  Logger.Log( 3, 'TAuthDatabase.SetLoginAuditEntry - start' );

  userInfo := TStringList.Create;
  try
    userInfo.Delimiter := '&';
    userInfo.StrictDelimiter := True;
    userInfo.DelimitedText := userStr;
    username := userInfo.Values['username'];
    fullname := userInfo.Values['fullname'];
    agency := userInfo.Values['agency'];
    userid := userInfo.Values['userId'];
    personnelid := userInfo.Values['personnelid'];

    if ServerConfig.auditEnabled then
    begin
      auditMasterId := GetNextSeqVal(uqMisc, 'SEQ_AUDIT_MASTERID');
      SetMasterAuditEntry(uqMisc, auditMasterId, 'AUTH', '', agency, personnelid, fullname, 'Login', '', 'emiMobile');
    end
    else
    begin
      Logger.Log( 3, 'SetSearchAuditEntry->SetMasterAuditEntry - auditEnabled = false' );
    end;
  finally
    userInfo.Free;
  end;
end;


end.
