Commit 8aff9228 by Mac Stephens

Update template to use most up to date structure and methods: mirroring…

Update template to use most up to date structure and methods: mirroring emiMobile, updated to version 0.1.1.0
parent fceb378c
...@@ -27,6 +27,9 @@ type ...@@ -27,6 +27,9 @@ type
implementation implementation
uses
View.ErrorPage;
procedure LoadConfig(LoadProc: TConfigLoadedProc); procedure LoadConfig(LoadProc: TConfigLoadedProc);
procedure OnSuccess(Response: IHttpResponse); procedure OnSuccess(Response: IHttpResponse);
...@@ -36,18 +39,23 @@ procedure LoadConfig(LoadProc: TConfigLoadedProc); ...@@ -36,18 +39,23 @@ procedure LoadConfig(LoadProc: TConfigLoadedProc);
begin begin
Config := TAppConfig.Create; Config := TAppConfig.Create;
try try
try
if Response.StatusCode = 200 then if Response.StatusCode = 200 then
begin begin
Obj := TJSObject(TJSJSON.parse(Response.ContentAsText)); Obj := TJSObject(TJSJSON.parse(Response.ContentAsText));
if JS.toString(Obj['AuthUrl']) <> '' then if Obj.HasOwnProperty('AuthUrl') and (JS.toString(Obj['AuthUrl']) <> '') then
Config.AuthUrl := JS.toString(Obj['AuthUrl']); Config.AuthUrl := JS.toString(Obj['AuthUrl']);
if JS.toString(Obj['ApiUrl']) <> '' then if Obj.HasOwnProperty('ApiUrl') and (JS.toString(Obj['ApiUrl']) <> '') then
Config.ApiUrl := JS.toString(Obj['ApiUrl']); Config.ApiUrl := JS.toString(Obj['ApiUrl']);
end; end;
finally except
TFViewErrorPage.Display('Unable to read config/config.json. Please correct the configuration JSON and reload the application.');
Exit;
end;
LoadProc(Config); LoadProc(Config);
finally
Config.Free; Config.Free;
end; end;
end; end;
......
...@@ -23,7 +23,7 @@ type ...@@ -23,7 +23,7 @@ type
public public
constructor Create; reintroduce; constructor Create; reintroduce;
destructor Destroy; override; destructor Destroy; override;
procedure Login(AUser, APassword, AClientVersion: string; ASuccess: TOnLoginSuccess; AError: TOnLoginError); procedure Login(AUser, APassword, AAgency, AClientVersion: string; ASuccess: TOnLoginSuccess; AError: TOnLoginError);
procedure VerifyClientVersion(AVersion: string; ACallback: TVersionCheckCallback); procedure VerifyClientVersion(AVersion: string; ACallback: TVersionCheckCallback);
procedure Logout; procedure Logout;
function GetToken: string; function GetToken: string;
...@@ -72,7 +72,7 @@ end; ...@@ -72,7 +72,7 @@ end;
constructor TAuthService.Create; constructor TAuthService.Create;
begin begin
FClient := TXDataWebClient.Create(nil); FClient := TXDataWebClient.Create(nil);
FClient.Connection := DMConnection.AuthConnection; FClient.Connection := dmConnection.authConnection;
end; end;
procedure TAuthService.DeleteToken; procedure TAuthService.DeleteToken;
...@@ -123,7 +123,7 @@ end; ...@@ -123,7 +123,7 @@ end;
procedure TAuthService.Login(AUser, APassword, AClientVersion: string; ASuccess: TOnLoginSuccess; procedure TAuthService.Login(AUser, APassword, AAgency, AClientVersion: string; ASuccess: TOnLoginSuccess;
AError: TOnLoginError); AError: TOnLoginError);
procedure OnLoad(Response: TXDataClientResponse); procedure OnLoad(Response: TXDataClientResponse);
...@@ -141,14 +141,14 @@ procedure TAuthService.Login(AUser, APassword, AClientVersion: string; ASuccess: ...@@ -141,14 +141,14 @@ procedure TAuthService.Login(AUser, APassword, AClientVersion: string; ASuccess:
end; end;
begin begin
if (AUser = '') or (APassword = '') then if (AUser = '') or (APassword = '') or (AAgency = '') then
begin begin
AError('Please enter a username and a password'); AError('Please enter a username, password, and agency');
Exit; Exit;
end; end;
FClient.RawInvoke( FClient.RawInvoke(
'IAuthService.Login', [AUser, APassword, AClientVersion], 'IAuthService.Login', [AUser, APassword, AAgency, AClientVersion],
@OnLoad, @OnError @OnLoad, @OnError
); );
end; end;
...@@ -189,7 +189,13 @@ function TAuthService.TokenExpired: Boolean; ...@@ -189,7 +189,13 @@ function TAuthService.TokenExpired: Boolean;
begin begin
if not Authenticated then if not Authenticated then
Exit(False); Exit(False);
try
Result := TJwtHelper.TokenExpired(GetToken); Result := TJwtHelper.TokenExpired(GetToken);
except
Result := True;
end;
if Result then
DeleteToken;
end; end;
function TAuthService.TokenPayload: JS.TJSObject; function TAuthService.TokenPayload: JS.TJSObject;
...@@ -243,7 +249,7 @@ end; ...@@ -243,7 +249,7 @@ end;
class function TJwtHelper.TokenExpired(AToken: string): Boolean; class function TJwtHelper.TokenExpired(AToken: string): Boolean;
begin begin
if not HasExpirationDate(AToken) then if not HasExpirationDate(AToken) then
Exit(False); Exit(True);
Result := TJSDate.now > toInteger(TokenExpirationDate(AToken).valueOf); Result := TJSDate.now > toInteger(TokenExpirationDate(AToken).valueOf);
end; end;
......
object DMConnection: TDMConnection object DMConnection: TDMConnection
Height = 264 Height = 264
Width = 395 Width = 395
object ApiConnection: TXDataWebConnection object apiConnection: TXDataWebConnection
URL = 'http://localhost:2004/emsys/template/api' URL = 'http://localhost:2001/emsys/template/api'
OnError = ApiConnectionError OnError = apiConnectionError
OnRequest = ApiConnectionRequest OnRequest = apiConnectionRequest
OnResponse = ApiConnectionResponse OnResponse = apiConnectionResponse
Left = 48 Left = 48
Top = 80 Top = 80
end end
object AuthConnection: TXDataWebConnection object authConnection: TXDataWebConnection
URL = 'http://localhost:2004/emsys/template/auth' URL = 'http://localhost:2001/emsys/template/auth'
OnError = AuthConnectionError OnError = authConnectionError
Left = 48 Left = 48
Top = 16 Top = 16
end end
......
...@@ -8,23 +8,23 @@ uses ...@@ -8,23 +8,23 @@ uses
type type
TDMConnection = class(TWebDataModule) TDMConnection = class(TWebDataModule)
ApiConnection: TXDataWebConnection; apiConnection: TXDataWebConnection;
AuthConnection: TXDataWebConnection; authConnection: TXDataWebConnection;
procedure ApiConnectionError(Error: TXDataWebConnectionError); procedure apiConnectionError(Error: TXDataWebConnectionError);
procedure ApiConnectionRequest(Args: TXDataWebConnectionRequest); procedure apiConnectionRequest(Args: TXDataWebConnectionRequest);
procedure ApiConnectionResponse(Args: TXDataWebConnectionResponse); procedure apiConnectionResponse(Args: TXDataWebConnectionResponse);
procedure AuthConnectionError(Error: TXDataWebConnectionError); procedure authConnectionError(Error: TXDataWebConnectionError);
private private
FUnauthorizedAccessProc: TUnauthorizedAccessProc; FUnauthorizedAccessProc: TUnauthorizedAccessProc;
public public
const clientVersion = '0.0.1'; const clientVersion = '0.1.1.0';
procedure InitApp(SuccessProc: TSuccessProc; procedure InitApp(SuccessProc: TSuccessProc;
UnauthorizedAccessProc: TUnauthorizedAccessProc); UnauthorizedAccessProc: TUnauthorizedAccessProc);
end; end;
var var
DMConnection: TDMConnection; dmConnection: TDMConnection;
implementation implementation
...@@ -32,70 +32,52 @@ uses ...@@ -32,70 +32,52 @@ uses
JS, Web, JS, Web,
XData.Web.Request, XData.Web.Request,
XData.Web.Response, XData.Web.Response,
Auth.Service; Auth.Service, View.ErrorPage;
{%CLASSGROUP 'Vcl.Controls.TControl'} {%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm} {$R *.dfm}
procedure TDMConnection.ApiConnectionError(Error: TXDataWebConnectionError); procedure TDMConnection.apiConnectionError(Error: TXDataWebConnectionError);
var
errorMsg: string;
begin begin
errorMsg := Error.ErrorMessage; TFViewErrorPage.DisplayConnectionError(Error);
if errorMsg = '' then
errorMsg := 'Connection error';
if Assigned(FUnauthorizedAccessProc) then
FUnauthorizedAccessProc(errorMsg)
else
ShowMessage(errorMsg);
end; end;
procedure TDMConnection.ApiConnectionRequest(Args: TXDataWebConnectionRequest); procedure TDMConnection.apiConnectionRequest(Args: TXDataWebConnectionRequest);
begin begin
if AuthService.Authenticated then if AuthService.Authenticated then
Args.Request.Headers.SetValue('Authorization', 'Bearer ' + AuthService.GetToken); Args.Request.Headers.SetValue('Authorization', 'Bearer ' + AuthService.GetToken);
end; end;
procedure TDMConnection.ApiConnectionResponse( procedure TDMConnection.apiConnectionResponse(
Args: TXDataWebConnectionResponse); Args: TXDataWebConnectionResponse);
begin begin
if Args.Response.StatusCode = 401 then if (Args.Response.StatusCode = 401) or
((Args.Response.StatusCode = 403) and (not AuthService.Authenticated)) then
FUnauthorizedAccessProc(Format('%d: %s',[Args.Response.StatusCode, Args.Response.ContentAsText])); FUnauthorizedAccessProc(Format('%d: %s',[Args.Response.StatusCode, Args.Response.ContentAsText]));
end; end;
procedure TDMConnection.AuthConnectionError(Error: TXDataWebConnectionError); procedure TDMConnection.authConnectionError(Error: TXDataWebConnectionError);
var
errorMsg: string;
begin begin
errorMsg := Error.ErrorMessage; TFViewErrorPage.DisplayConnectionError(Error);
if errorMsg = 'Error connecting to XData server' then
errorMsg := 'Error connecting to server. Please try again later.';
if Assigned(FUnauthorizedAccessProc) then
FUnauthorizedAccessProc(errorMsg)
else
ShowMessage(errorMsg);
end; end;
procedure TDMConnection.InitApp(SuccessProc: TSuccessProc; procedure TDMConnection.InitApp(SuccessProc: TSuccessProc;
UnauthorizedAccessProc: TUnauthorizedAccessProc); UnauthorizedAccessProc: TUnauthorizedAccessProc);
procedure ConfigLoaded(Config: TAppConfig); procedure ConfigLoaded(Config: TAppConfig);
begin begin
if Config.AuthUrl <> '' then if Config.AuthUrl <> '' then
AuthConnection.URL := Config.AuthUrl; authConnection.URL := Config.AuthUrl;
if Config.ApiUrl <> '' then if Config.ApiUrl <> '' then
ApiConnection.URL := Config.ApiUrl; apiConnection.URL := Config.ApiUrl;
AuthConnection.Open(SuccessProc); authConnection.Open(SuccessProc);
end; end;
begin begin
......
...@@ -12,11 +12,9 @@ procedure HideSpinner(SpinnerID: string); ...@@ -12,11 +12,9 @@ procedure HideSpinner(SpinnerID: string);
procedure ShowErrorModal(msg: string); procedure ShowErrorModal(msg: string);
function CalculateAge(DateOfBirth: TDateTime): Integer; function CalculateAge(DateOfBirth: TDateTime): Integer;
function FormatPhoneNumber(PhoneNumber: string): string; function FormatPhoneNumber(PhoneNumber: string): string;
procedure ApplyReportTitle(CurrentReportType: string);
procedure ShowToast(const MessageText: string; const ToastType: string = 'success'); procedure ShowToast(const MessageText: string; const ToastType: string = 'success');
procedure ShowConfirmationModal(msg, leftLabel, rightLabel: string; ConfirmProc: TProc<Boolean>); procedure ShowConfirmationModal(msg, leftLabel, rightLabel: string; ConfirmProc: TProc<Boolean>);
procedure ShowNotificationModal(msg: string); procedure ShowNotificationModal(msg: string);
procedure ShowVersionMismatchAndReload(const ErrorText, ClientVersion: string);
implementation implementation
...@@ -97,8 +95,8 @@ end; ...@@ -97,8 +95,8 @@ end;
procedure ShowErrorModal(msg: string); procedure ShowErrorModal(msg: string);
begin begin
asm asm
var modal = document.getElementById('main_errormodal'); var modal = document.getElementById('mdl_error');
var label = document.getElementById('main_lblmodal_body'); var label = document.getElementById('lbl_modal_body');
var reloadBtn = document.getElementById('btn_modal_restart'); var reloadBtn = document.getElementById('btn_modal_restart');
if (label) label.innerText = msg; if (label) label.innerText = msg;
...@@ -125,8 +123,8 @@ end; ...@@ -125,8 +123,8 @@ end;
procedure ShowNotificationModal(msg: string); procedure ShowNotificationModal(msg: string);
begin begin
asm asm
var modal = document.getElementById('main_notification_modal'); var modal = document.getElementById('mdl_notification');
var label = document.getElementById('main_notification_modal_body'); var label = document.getElementById('lbl_notification_body');
var closeBtn = document.getElementById('btn_modal_close'); var closeBtn = document.getElementById('btn_modal_close');
if (label) label.innerText = msg; if (label) label.innerText = msg;
...@@ -153,33 +151,12 @@ begin ...@@ -153,33 +151,12 @@ begin
end; end;
// ShowConfirmationModal displays a two-button modal with custom labels. // Note: The callback is True when the right (confirm) button is clicked.
// Params:
// - messageText: text shown in the modal body
// - leftButtonText: label for the left button (e.g., "Cancel")
// - rightButtonText: label for the right button (e.g., "Delete")
// - callback: procedure(confirmed: Boolean); confirmed = True if right button clicked
//
// Example:
// ShowConfirmationModal('Delete this?', 'Cancel', 'Delete',
// procedure(confirmed: Boolean)
// begin
// if confirmed then DeleteOrder();
// end);
// function ShowConfirmationModal(msg, leftLabel, rightLabel: string;): Boolean;
// if ShowConfirmationModal then
// doThing()
// else
// doOtherThing();
procedure ShowConfirmationModal(msg, leftLabel, rightLabel: string; ConfirmProc: TProc<Boolean>); procedure ShowConfirmationModal(msg, leftLabel, rightLabel: string; ConfirmProc: TProc<Boolean>);
begin begin
asm asm
var modal = document.getElementById('main_confirmation_modal'); var modal = document.getElementById('mdl_confirmation');
var body = document.getElementById('main_modal_body'); var body = document.getElementById('lbl_confirmation_body');
var btnLeft = document.getElementById('btn_confirm_left'); var btnLeft = document.getElementById('btn_confirm_left');
var btnRight = document.getElementById('btn_confirm_right'); var btnRight = document.getElementById('btn_confirm_right');
var bsModal; var bsModal;
...@@ -197,12 +174,12 @@ begin ...@@ -197,12 +174,12 @@ begin
btnLeft.onclick = function () { btnLeft.onclick = function () {
bsModal.hide(); bsModal.hide();
ConfirmProc(true); // user confirmed ConfirmProc(false);
}; };
btnRight.onclick = function () { btnRight.onclick = function () {
bsModal.hide(); bsModal.hide();
ConfirmProc(false); // user canceled ConfirmProc(true);
}; };
bsModal = new bootstrap.Modal(modal, { keyboard: false }); bsModal = new bootstrap.Modal(modal, { keyboard: false });
...@@ -280,8 +257,8 @@ begin ...@@ -280,8 +257,8 @@ begin
end; end;
asm asm
var toastEl = document.getElementById('bootstrapToast'); var toastEl = document.getElementById('toast_bootstrap');
var toastBody = document.getElementById('bootstrapToastBody'); var toastBody = document.getElementById('lbl_bootstrap_toast_body');
if (!toastEl || !toastBody) return; if (!toastEl || !toastBody) return;
...@@ -318,55 +295,6 @@ begin ...@@ -318,55 +295,6 @@ begin
end; end;
procedure ApplyReportTitle(CurrentReportType: string);
var
CrimeTitleElement: TJSHTMLElement;
begin
CrimeTitleElement := TJSHTMLElement(document.getElementById('crime_title'));
if Assigned(CrimeTitleElement) then
CrimeTitleElement.innerText := CurrentReportType
else
Console.Log('Element with ID "crime_title" not found.');
end;
procedure ShowVersionMismatchAndReload(const ErrorText, ClientVersion: string);
begin
asm
var dlg = document.createElement('dialog');
dlg.style.padding = '1rem';
dlg.style.maxWidth = '520px';
dlg.style.border = '1px solid #ccc';
dlg.style.borderRadius = '8px';
var title = document.createElement('h3');
title.textContent = 'template web app';
title.style.marginTop = '0';
var msg = document.createElement('pre');
msg.textContent = ErrorText;
msg.style.whiteSpace = 'pre-wrap';
msg.style.fontFamily = 'inherit';
var btnRow = document.createElement('div');
btnRow.style.display = 'flex';
btnRow.style.justifyContent = 'flex-end';
btnRow.style.marginTop = '1rem';
var btn = document.createElement('button');
btn.textContent = 'Reload';
btn.onclick = function () {
window.location.reload();
};
btnRow.appendChild(btn);
dlg.appendChild(title);
dlg.appendChild(msg);
dlg.appendChild(btnRow);
document.body.appendChild(dlg);
dlg.showModal();
end;
end;
end. end.
object fViewErrorPage: TFViewErrorPage
Left = 0
Top = 0
Width = 534
Height = 426
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
TabOrder = 1
object lbTitle: TWebLabel
Left = 24
Top = 24
Width = 128
Height = 13
Caption = 'Oops... an error occurred!'
ElementID = 'lb_title'
Transparent = False
end
object lbMessage: TWebLabel
Left = 24
Top = 56
Width = 42
Height = 13
Caption = 'Message'
ElementID = 'lb_message'
Transparent = False
end
end
<div class="container">
<div class="row justify-content-center mt-5">
<div class="col-12 col-sm-10 col-md-8 col-lg-6">
<div class="card shadow-sm border-danger">
<div id="lb_title"
class="card-header bg-danger text-white fw-semibold">
Error
</div>
<div class="card-body">
<div id="lb_message"
class="text-danger">
Message
</div>
</div>
<div class="card-footer bg-light text-end">
<a href="."
class="btn btn-outline-danger btn-sm">
Reload web application
</a>
</div>
</div>
</div>
</div>
</div>
unit View.ErrorPage;
interface
uses
System.SysUtils, System.Classes, WEBLib.Graphics, WEBLib.Controls, WEBLib.Forms, WEBLib.Dialogs,
Vcl.Controls, Vcl.StdCtrls,
XData.Web.Connection, WEBLib.StdCtrls;
type
TFViewErrorPage = class(TWebForm)
lbTitle: TWebLabel;
lbMessage: TWebLabel;
public
class procedure Display(AErrorMessage: string);
class procedure DisplayConnectionError(AError: TXDataWebConnectionError);
end;
var
fViewErrorPage: TFViewErrorPage;
implementation
{$R *.dfm}
{ TFViewErrorPage }
class procedure TFViewErrorPage.Display(AErrorMessage: string);
procedure AfterCreateProc(AForm: TObject);
begin
TFViewErrorPage(AForm).lbMessage.Caption := AErrorMessage;
end;
begin
if Assigned(fViewErrorPage) then
fViewErrorPage.Free;
fViewErrorPage := TFViewErrorPage.CreateNew(@AfterCreateProc);
end;
class procedure TFViewErrorPage.DisplayConnectionError(
AError: TXDataWebConnectionError);
begin
Display(AError.ErrorMessage + ': ' + AError.RequestUrl);
end;
end.
object FViewLogin: TFViewLogin object fViewLogin: TFViewLogin
Width = 1322 Width = 1322
Height = 764 Height = 764
CSSLibrary = cssBootstrap CSSLibrary = cssBootstrap
...@@ -91,6 +91,17 @@ object FViewLogin: TFViewLogin ...@@ -91,6 +91,17 @@ object FViewLogin: TFViewLogin
TextHint = 'Password' TextHint = 'Password'
WidthPercent = 100.000000000000000000 WidthPercent = 100.000000000000000000
end end
object lucbAgency: TWebLookupComboBox
Left = 240
Top = 190
Width = 121
Height = 21
ElementID = 'lucb_agency'
ElementFont = efCSS
TextHint = 'Agency'
ItemIndex = -1
TabOrder = 2
end
object btnLogin: TWebButton object btnLogin: TWebButton
Left = 240 Left = 240
Top = 190 Top = 190
...@@ -107,7 +118,7 @@ object FViewLogin: TFViewLogin ...@@ -107,7 +118,7 @@ object FViewLogin: TFViewLogin
HeightPercent = 100.000000000000000000 HeightPercent = 100.000000000000000000
ParentFont = False ParentFont = False
Role = 'null' Role = 'null'
TabOrder = 2 TabOrder = 3
WidthPercent = 100.000000000000000000 WidthPercent = 100.000000000000000000
OnClick = btnLoginClick OnClick = btnLoginClick
end end
...@@ -125,7 +136,7 @@ object FViewLogin: TFViewLogin ...@@ -125,7 +136,7 @@ object FViewLogin: TFViewLogin
Font.Style = [] Font.Style = []
ParentFont = False ParentFont = False
Role = 'null' Role = 'null'
TabOrder = 3 TabOrder = 4
Visible = False Visible = False
object lblMessage: TWebLabel object lblMessage: TWebLabel
Left = 16 Left = 16
...@@ -150,7 +161,7 @@ object FViewLogin: TFViewLogin ...@@ -150,7 +161,7 @@ object FViewLogin: TFViewLogin
end end
end end
object xdwcLogin: TXDataWebClient object xdwcLogin: TXDataWebClient
Connection = DMConnection.AuthConnection Connection = dmConnection.authConnection
Left = 492 Left = 492
Top = 102 Top = 102
end end
......
...@@ -22,6 +22,10 @@ ...@@ -22,6 +22,10 @@
</div> </div>
<div class="mb-3"> <div class="mb-3">
<select id="lucb_agency" class="form-select form-select-lg w-100" aria-label="Agency"></select>
</div>
<div class="mb-3">
<button id="btn_login" class="btn btn-primary btn-lg w-100">Login</button> <button id="btn_login" class="btn btn-primary btn-lg w-100">Login</button>
</div> </div>
......
...@@ -14,6 +14,7 @@ type ...@@ -14,6 +14,7 @@ type
edtUsername: TWebEdit; edtUsername: TWebEdit;
edtPassword: TWebEdit; edtPassword: TWebEdit;
btnLogin: TWebButton; btnLogin: TWebButton;
lucbAgency: TWebLookupComboBox;
pnlMessage: TWebPanel; pnlMessage: TWebPanel;
lblMessage: TWebLabel; lblMessage: TWebLabel;
btnCloseNotification: TWebButton; btnCloseNotification: TWebButton;
...@@ -28,13 +29,14 @@ type ...@@ -28,13 +29,14 @@ type
FMessage: string; FMessage: string;
procedure ShowNotification(Notification: string); procedure ShowNotification(Notification: string);
procedure HideNotification; procedure HideNotification;
procedure GetAgencyConfigList;
public public
class procedure Display(LoginProc: TSuccessProc); overload; class procedure Display(LoginProc: TSuccessProc); overload;
class procedure Display(LoginProc: TSuccessProc; AMsg: string); overload; class procedure Display(LoginProc: TSuccessProc; AMsg: string); overload;
end; end;
var var
FViewLogin: TFViewLogin; fViewLogin: TFViewLogin;
implementation implementation
...@@ -58,15 +60,15 @@ procedure TFViewLogin.btnLoginClick(Sender: TObject); ...@@ -58,15 +60,15 @@ procedure TFViewLogin.btnLoginClick(Sender: TObject);
procedure AuthConnectionOpened; procedure AuthConnectionOpened;
begin begin
AuthService.Login( AuthService.Login(
edtUsername.Text, edtPassword.Text, DMConnection.clientVersion, edtUsername.Text, edtPassword.Text, lucbAgency.Value, dmConnection.clientVersion,
@LoginSuccess, @LoginSuccess,
@LoginError @LoginError
); );
end; end;
begin begin
if not DMConnection.AuthConnection.Connected then if not dmConnection.authConnection.Connected then
DMConnection.AuthConnection.Open(@AuthConnectionOpened) dmConnection.authConnection.Open(@AuthConnectionOpened)
else else
AuthConnectionOpened; AuthConnectionOpened;
end; end;
...@@ -84,10 +86,10 @@ class procedure TFViewLogin.Display(LoginProc: TSuccessProc; AMsg: string); ...@@ -84,10 +86,10 @@ class procedure TFViewLogin.Display(LoginProc: TSuccessProc; AMsg: string);
end; end;
begin begin
if Assigned(FViewLogin) then if Assigned(fViewLogin) then
FViewLogin.Free; fViewLogin.Free;
FViewLogin := TFViewLogin.CreateNew(@FormCreate); fViewLogin := TFViewLogin.CreateNew(@FormCreate);
FViewLogin.FLoginProc := LoginProc; fViewLogin.FLoginProc := LoginProc;
end; end;
procedure TFViewLogin.HideNotification; procedure TFViewLogin.HideNotification;
...@@ -113,8 +115,8 @@ end; ...@@ -113,8 +115,8 @@ end;
procedure TFViewLogin.WebFormShow(Sender: TObject); procedure TFViewLogin.WebFormShow(Sender: TObject);
begin begin
console.log(DMConnection.clientVersion); GetAgencyConfigList;
FViewLogin.lblClientVersion.Caption := 'v' + DMConnection.clientVersion; fViewLogin.lblClientVersion.Caption := 'v' + dmConnection.clientVersion;
if FMessage <> '' then if FMessage <> '' then
ShowNotification(FMessage) ShowNotification(FMessage)
else else
...@@ -122,4 +124,34 @@ begin ...@@ -122,4 +124,34 @@ begin
end; end;
procedure TFViewLogin.GetAgencyConfigList;
procedure OnLoad(Response: TXDataClientResponse);
var
data: TJSArray;
item: TJSObject;
agency: string;
i: Integer;
begin
data := TJSArray(TJSObject(Response.Result)['data']);
lucbAgency.LookupValues.Clear;
for i := 0 to data.Length - 1 do
begin
item := TJSObject(data[i]);
agency := string(item['agency']);
lucbAgency.LookupValues.AddPair(agency, agency + ' - ' + string(item['name']));
end;
if data.Length = 1 then
lucbAgency.Value := agency;
end;
procedure OnError(Error: TXDataClientError);
begin
ShowNotification(Error.ErrorMessage);
end;
begin
xdwcLogin.RawInvoke('IAuthService.GetAgencyConfigList', [], @OnLoad, @OnError);
end;
end. end.
object FViewMain: TFViewMain object fViewMain: TFViewMain
Width = 1322 Width = 1322
Height = 764 Height = 764
CSSLibrary = cssBootstrap CSSLibrary = cssBootstrap
...@@ -22,16 +22,6 @@ object FViewMain: TFViewMain ...@@ -22,16 +22,6 @@ object FViewMain: TFViewMain
Transparent = False Transparent = False
WidthPercent = 100.000000000000000000 WidthPercent = 100.000000000000000000
end end
object lblUserProfile: TWebLinkLabel
Left = 529
Top = 21
Width = 59
Height = 14
ElementID = 'lbl_user_profile'
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
Caption = ' User Profile'
end
object lblLogout: TWebLinkLabel object lblLogout: TWebLinkLabel
Left = 547 Left = 547
Top = 55 Top = 55
...@@ -51,6 +41,7 @@ object FViewMain: TFViewMain ...@@ -51,6 +41,7 @@ object FViewMain: TFViewMain
ElementID = 'lbl_home' ElementID = 'lbl_home'
HeightPercent = 100.000000000000000000 HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000 WidthPercent = 100.000000000000000000
OnClick = lblHomeClick
Caption = 'Home' Caption = 'Home'
end end
object lblAppTitle: TWebLabel object lblAppTitle: TWebLabel
...@@ -58,7 +49,7 @@ object FViewMain: TFViewMain ...@@ -58,7 +49,7 @@ object FViewMain: TFViewMain
Top = 33 Top = 33
Width = 42 Width = 42
Height = 14 Height = 14
Caption = 'App Title' Caption = 'EM Systems Template App'
ElementID = 'lbl_app_title' ElementID = 'lbl_app_title'
ElementPosition = epRelative ElementPosition = epRelative
HeightPercent = 100.000000000000000000 HeightPercent = 100.000000000000000000
...@@ -117,7 +108,7 @@ object FViewMain: TFViewMain ...@@ -117,7 +108,7 @@ object FViewMain: TFViewMain
WidthPercent = 100.000000000000000000 WidthPercent = 100.000000000000000000
end end
object xdwcMain: TXDataWebClient object xdwcMain: TXDataWebClient
Connection = DMConnection.ApiConnection Connection = dmConnection.apiConnection
Left = 114 Left = 114
Top = 230 Top = 230
end end
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
<nav class="navbar navbar-expand-lg bg-body-tertiary border-bottom shadow-sm"> <nav class="navbar navbar-expand-lg bg-body-tertiary border-bottom shadow-sm">
<div class="container-fluid"> <div class="container-fluid">
<div class="d-flex align-items-center gap-2"> <div class="d-flex align-items-center gap-2">
<a id="lbl_app_title" class="navbar-brand fw-semibold" href="index.html">Koehler-Gibson Orders</a> <a id="lbl_app_title" class="navbar-brand fw-semibold" href="index.html">EM Systems Template App</a>
<span id="lbl_version" class="badge text-bg-light border text-muted fw-normal"></span> <span id="lbl_version" class="badge text-bg-light border text-muted fw-normal"></span>
</div> </div>
...@@ -21,11 +21,6 @@ ...@@ -21,11 +21,6 @@
<i class="fa fa-home fa-fw"></i><span>Home</span> <i class="fa fa-home fa-fw"></i><span>Home</span>
</a> </a>
</li> </li>
<li>
<a class="dropdown-item d-flex align-items-center gap-2" id="lbl_user_profile" href="#">
<i class="fa fa-user fa-fw"></i><span>User Profile</span>
</a>
</li>
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li> <li>
<a class="dropdown-item d-flex align-items-center gap-2 text-danger" id="lbl_logout" href="#"> <a class="dropdown-item d-flex align-items-center gap-2 text-danger" id="lbl_logout" href="#">
...@@ -88,7 +83,7 @@ ...@@ -88,7 +83,7 @@
Please contact EMSystems to solve the issue. Please contact EMSystems to solve the issue.
</div> </div>
<div class="modal-footer justify-content-center"> <div class="modal-footer justify-content-center">
<button type="button" id="btn_modal_restart" class="btn btn-primary">Back to Orders</button> <button type="button" id="btn_modal_restart" class="btn btn-primary">Reload application</button>
</div> </div>
</div> </div>
</div> </div>
......
...@@ -12,7 +12,6 @@ type ...@@ -12,7 +12,6 @@ type
TFViewMain = class(TWebForm) TFViewMain = class(TWebForm)
pnlMain: TWebPanel; pnlMain: TWebPanel;
lblUsername: TWebLabel; lblUsername: TWebLabel;
lblUserProfile: TWebLinkLabel;
lblHome: TWebLinkLabel; lblHome: TWebLinkLabel;
lblLogout: TWebLinkLabel; lblLogout: TWebLinkLabel;
lblVersion: TWebLabel; lblVersion: TWebLabel;
...@@ -21,16 +20,18 @@ type ...@@ -21,16 +20,18 @@ type
xdwcMain: TXDataWebClient; xdwcMain: TXDataWebClient;
procedure WebFormCreate(Sender: TObject); procedure WebFormCreate(Sender: TObject);
procedure lblLogoutClick(Sender: TObject); procedure lblLogoutClick(Sender: TObject);
procedure lblHomeClick(Sender: TObject);
private private
FChildForm: TWebForm; FChildForm: TWebForm;
FLogoutProc: TLogoutProc; FLogoutProc: TLogoutProc;
procedure ShowForm(aFormClass: TWebFormClass); procedure ShowForm(aFormClass: TWebFormClass);
public public
destructor Destroy; override;
class procedure Display(logoutProc: TLogoutProc); class procedure Display(logoutProc: TLogoutProc);
end; end;
var var
FViewMain: TFViewMain; fViewMain: TFViewMain;
implementation implementation
...@@ -46,11 +47,23 @@ var ...@@ -46,11 +47,23 @@ var
begin begin
userName := JS.toString(AuthService.TokenPayload.Properties['user_name']); userName := JS.toString(AuthService.TokenPayload.Properties['user_name']);
lblUsername.Caption := userName; lblUsername.Caption := userName;
lblVersion.Caption := 'v' + DMConnection.clientVersion; lblVersion.Caption := 'v' + dmConnection.clientVersion;
ShowForm(TFTest); ShowForm(TFTest);
end; end;
destructor TFViewMain.Destroy;
begin
if fViewMain = Self then
fViewMain := nil;
inherited;
end;
procedure TFViewMain.lblHomeClick(Sender: TObject);
begin
ShowForm(TFTest);
end;
procedure TFViewMain.lblLogoutClick(Sender: TObject); procedure TFViewMain.lblLogoutClick(Sender: TObject);
begin begin
if Assigned(FLogoutProc) then if Assigned(FLogoutProc) then
...@@ -66,10 +79,10 @@ end; ...@@ -66,10 +79,10 @@ end;
class procedure TFViewMain.Display(logoutProc: TLogoutProc); class procedure TFViewMain.Display(logoutProc: TLogoutProc);
begin begin
if Assigned(FViewMain) then if Assigned(fViewMain) then
FViewMain.Free; fViewMain.Free;
FViewMain := TFViewMain.CreateNew; fViewMain := TFViewMain.CreateNew;
FViewMain.FLogoutProc := logoutProc; fViewMain.FLogoutProc := logoutProc;
end; end;
end. end.
......
object FTest: TFTest object fTest: TFTest
Width = 640 Width = 640
Height = 480 Height = 480
CSSLibrary = cssBootstrap CSSLibrary = cssBootstrap
...@@ -47,7 +47,7 @@ object FTest: TFTest ...@@ -47,7 +47,7 @@ object FTest: TFTest
OnChange = memoTestDebugChange OnChange = memoTestDebugChange
end end
object xdwcTest: TXDataWebClient object xdwcTest: TXDataWebClient
Connection = DMConnection.ApiConnection Connection = dmConnection.apiConnection
Left = 464 Left = 464
Top = 208 Top = 208
end end
......
...@@ -23,12 +23,12 @@ type ...@@ -23,12 +23,12 @@ type
end; end;
var var
FTest: TFTest; fTest: TFTest;
implementation implementation
uses uses
Auth.Service; Auth.Service, Utils;
procedure TFTest.AddLine(const s: string); procedure TFTest.AddLine(const s: string);
begin begin
...@@ -71,13 +71,14 @@ var ...@@ -71,13 +71,14 @@ var
messageText: string; messageText: string;
requiredVersion: string; requiredVersion: string;
begin begin
try
memoTestDebug.Visible := True; memoTestDebug.Visible := True;
memoTestDebug.Lines.Clear; memoTestDebug.Lines.Clear;
AddLine('--- request ---'); AddLine('--- request ---');
AddLine('api url: ' + DMConnection.ApiConnection.URL); AddLine('api url: ' + dmConnection.apiConnection.URL);
AddLine('auth url: ' + DMConnection.AuthConnection.URL); AddLine('auth url: ' + dmConnection.authConnection.URL);
AddLine('clientVersion const: ' + DMConnection.clientVersion); AddLine('clientVersion const: ' + dmConnection.clientVersion);
AddLine(''); AddLine('');
AddLine('--- token / claims ---'); AddLine('--- token / claims ---');
...@@ -87,26 +88,13 @@ begin ...@@ -87,26 +88,13 @@ begin
AddLine(''); AddLine('');
AddLine('calling IApiService.TestApi ...'); AddLine('calling IApiService.TestApi ...');
try
response := await(xdwcTest.RawInvokeAsync('IApiService.TestApi', [messageText])); response := await(xdwcTest.RawInvokeAsync('IApiService.TestApi', [messageText]));
except
on E: Exception do
begin
AddLine('');
AddLine('--- api exception ---');
AddLine(E.Message);
Exit;
end;
end;
AddLine(''); AddLine('');
AddLine('--- api response ---'); AddLine('--- api response ---');
if not Assigned(response.Result) then if not Assigned(response.Result) then
begin raise Exception.Create('The server returned an empty API response.');
AddLine('response.Result is nil');
Exit;
end;
resultObj := TJSObject(response.Result); resultObj := TJSObject(response.Result);
...@@ -119,9 +107,15 @@ begin ...@@ -119,9 +107,15 @@ begin
AddLine(''); AddLine('');
AddLine('--- version compare (client-side) ---'); AddLine('--- version compare (client-side) ---');
AddLine('clientVersion const: ' + DMConnection.clientVersion); AddLine('clientVersion const: ' + dmConnection.clientVersion);
AddLine('requiredWebClientVersion: ' + requiredVersion); AddLine('requiredWebClientVersion: ' + requiredVersion);
AddLine('match: ' + BoolToStr(DMConnection.clientVersion = requiredVersion, True)); AddLine('match: ' + BoolToStr(dmConnection.clientVersion = requiredVersion, True));
except
on E: EXDataClientRequestException do
Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
on E: Exception do
Utils.ShowErrorModal(E.Message);
end;
end; end;
procedure TFTest.memoTestDebugChange(Sender: TObject); procedure TFTest.memoTestDebugChange(Sender: TObject);
......
...@@ -2,16 +2,18 @@ program templateWebApp; ...@@ -2,16 +2,18 @@ program templateWebApp;
uses uses
Vcl.Forms, Vcl.Forms,
System.SysUtils,
XData.Web.Connection, XData.Web.Connection,
WEBLib.Dialogs, WEBLib.Dialogs,
Auth.Service in 'Auth.Service.pas', Auth.Service in 'Auth.Service.pas',
App.Types in 'App.Types.pas', App.Types in 'App.Types.pas',
ConnectionModule in 'ConnectionModule.pas' {DMConnection: TWebDataModule}, ConnectionModule in 'ConnectionModule.pas' {dmConnection: TWebDataModule},
App.Config in 'App.Config.pas', App.Config in 'App.Config.pas',
View.Main in 'View.Main.pas' {FViewMain: TWebForm} {*.html}, View.Main in 'View.Main.pas' {fViewMain: TWebForm} {*.html},
Utils in 'Utils.pas', Utils in 'Utils.pas',
View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html}, View.Login in 'View.Login.pas' {fViewLogin: TWebForm} {*.html},
View.Test in 'View.Test.pas' {FTest: TWebForm} {*.html}; View.Test in 'View.Test.pas' {fTest: TWebForm} {*.html},
View.ErrorPage in 'View.ErrorPage.pas' {fViewErrorPage: TWebForm} {*.html};
{$R *.res} {$R *.res}
...@@ -21,14 +23,14 @@ procedure DisplayMainView; ...@@ -21,14 +23,14 @@ procedure DisplayMainView;
procedure ConnectProc; procedure ConnectProc;
begin begin
if Assigned(FViewLogin) then if Assigned(fViewLogin) then
FViewLogin.Free; FreeAndNil(fViewLogin);
TFViewMain.Display(@DisplayLoginView); TFViewMain.Display(@DisplayLoginView);
end; end;
begin begin
if not DMConnection.ApiConnection.Connected then if not dmConnection.apiConnection.Connected then
DMConnection.ApiConnection.Open(@ConnectProc) dmConnection.apiConnection.Open(@ConnectProc)
else else
ConnectProc; ConnectProc;
end; end;
...@@ -36,9 +38,9 @@ end; ...@@ -36,9 +38,9 @@ end;
procedure DisplayLoginView(AMessage: string = ''); procedure DisplayLoginView(AMessage: string = '');
begin begin
AuthService.Logout; AuthService.Logout;
DMConnection.ApiConnection.Connected := False; dmConnection.apiConnection.Connected := False;
if Assigned(FViewMain) then if Assigned(fViewMain) then
FViewMain.Free; fViewMain.Free;
TFViewLogin.Display(@DisplayMainView, AMessage); TFViewLogin.Display(@DisplayMainView, AMessage);
end; end;
...@@ -51,7 +53,7 @@ procedure AfterVerifyClientVersion(Success: Boolean; Error: string); ...@@ -51,7 +53,7 @@ procedure AfterVerifyClientVersion(Success: Boolean; Error: string);
begin begin
if not Success then if not Success then
begin begin
ShowVersionMismatchAndReload(Error, DMConnection.clientVersion); TFViewErrorPage.Display(Error + sLineBreak + sLineBreak + 'Current client version: v' + dmConnection.clientVersion);
Exit; Exit;
end; end;
...@@ -63,14 +65,14 @@ end; ...@@ -63,14 +65,14 @@ end;
procedure StartApplication; procedure StartApplication;
begin begin
AuthService.VerifyClientVersion(DMConnection.clientVersion, @AfterVerifyClientVersion); AuthService.VerifyClientVersion(dmConnection.clientVersion, @AfterVerifyClientVersion);
end; end;
begin begin
Application.Initialize; Application.Initialize;
Application.MainFormOnTaskbar := True; Application.MainFormOnTaskbar := True;
Application.CreateForm(TDMConnection, DMConnection); Application.CreateForm(TdmConnection, dmConnection);
Application.Run; Application.Run;
DMConnection.InitApp(@StartApplication, @UnauthorizedAccessProc); dmConnection.InitApp(@StartApplication, @UnauthorizedAccessProc);
end. end.
...@@ -94,11 +94,11 @@ ...@@ -94,11 +94,11 @@
<DCC_RemoteDebug>false</DCC_RemoteDebug> <DCC_RemoteDebug>false</DCC_RemoteDebug>
<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo> <VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>
<VerInfo_Locale>1033</VerInfo_Locale> <VerInfo_Locale>1033</VerInfo_Locale>
<VerInfo_Keys>CompanyName=;FileDescription=$(MSBuildProjectName);FileVersion=0.9.8.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProgramID=com.embarcadero.$(MSBuildProjectName);ProductName=$(MSBuildProjectName);ProductVersion=0.9.8.0;Comments=;LastCompiledTime=2018/08/27 15:18:29</VerInfo_Keys> <VerInfo_Keys>CompanyName=;FileDescription=$(MSBuildProjectName);FileVersion=0.1.1.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProgramID=com.embarcadero.$(MSBuildProjectName);ProductName=$(MSBuildProjectName);ProductVersion=0.9.8.0;Comments=;LastCompiledTime=2018/08/27 15:18:29</VerInfo_Keys>
<AppDPIAwarenessMode>PerMonitor</AppDPIAwarenessMode> <AppDPIAwarenessMode>PerMonitor</AppDPIAwarenessMode>
<VerInfo_MajorVer>0</VerInfo_MajorVer> <VerInfo_MajorVer>0</VerInfo_MajorVer>
<VerInfo_MinorVer>9</VerInfo_MinorVer> <VerInfo_MinorVer>1</VerInfo_MinorVer>
<VerInfo_Release>8</VerInfo_Release> <VerInfo_Release>1</VerInfo_Release>
<TMSWebBrowser>1</TMSWebBrowser> <TMSWebBrowser>1</TMSWebBrowser>
<TMSUseJSDebugger>2</TMSUseJSDebugger> <TMSUseJSDebugger>2</TMSUseJSDebugger>
<TMSWebSingleInstance>1</TMSWebSingleInstance> <TMSWebSingleInstance>1</TMSWebSingleInstance>
...@@ -126,23 +126,28 @@ ...@@ -126,23 +126,28 @@
<DCCReference Include="Auth.Service.pas"/> <DCCReference Include="Auth.Service.pas"/>
<DCCReference Include="App.Types.pas"/> <DCCReference Include="App.Types.pas"/>
<DCCReference Include="ConnectionModule.pas"> <DCCReference Include="ConnectionModule.pas">
<Form>DMConnection</Form> <Form>dmConnection</Form>
<DesignClass>TWebDataModule</DesignClass> <DesignClass>TWebDataModule</DesignClass>
</DCCReference> </DCCReference>
<DCCReference Include="App.Config.pas"/> <DCCReference Include="App.Config.pas"/>
<DCCReference Include="View.Main.pas"> <DCCReference Include="View.Main.pas">
<Form>FViewMain</Form> <Form>fViewMain</Form>
<FormType>dfm</FormType> <FormType>dfm</FormType>
<DesignClass>TWebForm</DesignClass> <DesignClass>TWebForm</DesignClass>
</DCCReference> </DCCReference>
<DCCReference Include="Utils.pas"/> <DCCReference Include="Utils.pas"/>
<DCCReference Include="View.Login.pas"> <DCCReference Include="View.Login.pas">
<Form>FViewLogin</Form> <Form>fViewLogin</Form>
<FormType>dfm</FormType> <FormType>dfm</FormType>
<DesignClass>TWebForm</DesignClass> <DesignClass>TWebForm</DesignClass>
</DCCReference> </DCCReference>
<DCCReference Include="View.Test.pas"> <DCCReference Include="View.Test.pas">
<Form>FTest</Form> <Form>fTest</Form>
<FormType>dfm</FormType>
<DesignClass>TWebForm</DesignClass>
</DCCReference>
<DCCReference Include="View.ErrorPage.pas">
<Form>fViewErrorPage</Form>
<FormType>dfm</FormType> <FormType>dfm</FormType>
<DesignClass>TWebForm</DesignClass> <DesignClass>TWebForm</DesignClass>
</DCCReference> </DCCReference>
...@@ -171,10 +176,10 @@ ...@@ -171,10 +176,10 @@
<Source Name="MainSource">templateWebApp.dpr</Source> <Source Name="MainSource">templateWebApp.dpr</Source>
</Source> </Source>
<Excluded_Packages> <Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcboffice2k290.bpl">Embarcadero C++Builder Office 2000 Servers Package</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\bcboffice2k370.bpl">Embarcadero C++Builder Office 2000 Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcbofficexp290.bpl">Embarcadero C++Builder Office XP Servers Package</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\bcbofficexp370.bpl">Embarcadero C++Builder Office XP Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dcloffice2k290.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\dcloffice2k370.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dclofficexp290.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\dclofficexp370.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages>
</Excluded_Packages> </Excluded_Packages>
</Delphi.Personality> </Delphi.Personality>
<Deployment Version="5"> <Deployment Version="5">
......
[Settings] [Settings]
MemoLogLevel=5 MemoLogLevel=5
FileLogLevel=5 FileLogLevel=5
LogFileNum=44 LogFileNum=47
DevMode=0 DevMode=0
webClientVersion=0.0.1 webClientVersion=0.1.1.0
[Database] [Postgres]
--Server=192.168.116.129 Server=192.168.102.10
Server=192.168.102.131 Port=5432
--Port= Database=lems_wcso
Database=sleepdb Username=postgres
--Username= Password=emsys01
--Password=
[SMTP] [SMTP]
--Type=useExplicitTLS --Type=useExplicitTLS
......
...@@ -3,29 +3,30 @@ object ApiDatabase: TApiDatabase ...@@ -3,29 +3,30 @@ object ApiDatabase: TApiDatabase
Height = 358 Height = 358
Width = 519 Width = 519
object UniQuery1: TUniQuery object UniQuery1: TUniQuery
Connection = ucDatabase
SQL.Strings = ( SQL.Strings = (
'') '')
Left = 73 Left = 73
Top = 148 Top = 148
end end
object MySQLUniProvider1: TMySQLUniProvider object PostgreSQLUniProvider1: TPostgreSQLUniProvider
Left = 202 Left = 202
Top = 60 Top = 60
end end
object UniQuery2: TUniQuery object UniQuery2: TUniQuery
Connection = ucDatabase
SQL.Strings = ( SQL.Strings = (
'') '')
Left = 179 Left = 179
Top = 148 Top = 148
end end
object ucHST: TUniConnection object ucDatabase: TUniConnection
ProviderName = 'MySQL' ProviderName = 'PostgreSQL'
Database = 'sleepdb' Port = 5432
Username = 'hstuser' SpecificOptions.Strings = (
Server = '192.168.116.135' 'PostgreSQL.Schema=lems, avl, entcad')
LoginPrompt = False LoginPrompt = False
Left = 81 Left = 81
Top = 59 Top = 59
EncryptedPassword = '9AFF92FF8CFF86FF8CFFDEFFCFFFCEFF'
end end
end end
...@@ -5,14 +5,14 @@ interface ...@@ -5,14 +5,14 @@ interface
uses uses
System.SysUtils, System.Classes, Data.DB, MemDS, DBAccess, Uni, UniProvider, System.SysUtils, System.Classes, Data.DB, MemDS, DBAccess, Uni, UniProvider,
PostgreSQLUniProvider, System.Variants, System.Generics.Collections, System.IniFiles, PostgreSQLUniProvider, System.Variants, System.Generics.Collections, System.IniFiles,
Common.Logging, Vcl.Forms, MySQLUniProvider, Common.Ini; Common.Logging, Vcl.Forms, Common.Ini;
type type
TApiDatabase = class(TDataModule) TApiDatabase = class(TDataModule)
UniQuery1: TUniQuery; UniQuery1: TUniQuery;
MySQLUniProvider1: TMySQLUniProvider; PostgreSQLUniProvider1: TPostgreSQLUniProvider;
UniQuery2: TUniQuery; UniQuery2: TUniQuery;
ucHST: TUniConnection; ucDatabase: TUniConnection;
procedure DataModuleCreate(Sender: TObject); procedure DataModuleCreate(Sender: TObject);
private private
{ Private declarations } { Private declarations }
...@@ -36,16 +36,13 @@ procedure TApiDatabase.DataModuleCreate(Sender: TObject); ...@@ -36,16 +36,13 @@ procedure TApiDatabase.DataModuleCreate(Sender: TObject);
begin begin
Logger.Log(5, 'TApiDatabase.DataModuleCreate'); Logger.Log(5, 'TApiDatabase.DataModuleCreate');
try try
ucHST.Database := IniEntries.dbDatabase; IniEntries.ConfigureConnection(ucDatabase);
ucHST.Server := IniEntries.dbServer; ucDatabase.Connect;
ucHST.Port := IniEntries.dbPort; ucDatabase.ExecSQL('set search_path to lems, avl, entcad, public');
ucHST.Username := IniEntries.dbUsername;
ucHST.Password := IniEntries.dbPassword;
ucHST.Connect;
except except
on E: Exception do on E: Exception do
begin begin
Logger.Log(2, '--TAuthDatabase.DataModuleCreate -Error connecting to database: ' + E.Message); Logger.Log(2, '--TApiDatabase.DataModuleCreate -Error connecting to database: ' + E.Message);
end; end;
end; end;
end; end;
......
...@@ -16,6 +16,9 @@ object ApiServerModule: TApiServerModule ...@@ -16,6 +16,9 @@ object ApiServerModule: TApiServerModule
SwaggerUIOptions.TryItOutEnabled = True SwaggerUIOptions.TryItOutEnabled = True
Left = 89 Left = 89
Top = 112 Top = 112
object XDataServerForward: TSparkleForwardMiddleware
OnAcceptProxy = XDataServerForwardAcceptProxy
end
object XDataServerLogging: TSparkleGenericMiddleware object XDataServerLogging: TSparkleGenericMiddleware
OnMiddlewareCreate = XDataServerLoggingMiddlewareCreate OnMiddlewareCreate = XDataServerLoggingMiddlewareCreate
end end
...@@ -24,9 +27,8 @@ object ApiServerModule: TApiServerModule ...@@ -24,9 +27,8 @@ object ApiServerModule: TApiServerModule
object XDataServerCompress: TSparkleCompressMiddleware object XDataServerCompress: TSparkleCompressMiddleware
end end
object XDataServerJWT: TSparkleJwtMiddleware object XDataServerJWT: TSparkleJwtMiddleware
ForbidAnonymousAccess = True ForbidAnonymousAccess = False
OnGetSecret = XDataServerJWTGetSecret OnGetSecret = XDataServerJWTGetSecret
OnForbidRequest = XDataServerJWTForbidRequest
end end
end end
end end
...@@ -15,20 +15,20 @@ uses ...@@ -15,20 +15,20 @@ uses
Sparkle.HttpServer.Module, Sparkle.HttpServer.Context, Sparkle.HttpServer.Module, Sparkle.HttpServer.Context,
Sparkle.Comp.CompressMiddleware, Sparkle.Comp.CorsMiddleware, Sparkle.Comp.CompressMiddleware, Sparkle.Comp.CorsMiddleware,
Sparkle.Comp.GenericMiddleware, Aurelius.Drivers.UniDac, UniProvider, Sparkle.Comp.GenericMiddleware, Aurelius.Drivers.UniDac, UniProvider,
Data.DB, DBAccess, Uni; Data.DB, DBAccess, Uni, Sparkle.Comp.ForwardMiddleware;
type type
TApiServerModule = class(TDataModule) TApiServerModule = class(TDataModule)
SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher; SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher;
XDataServer: TXDataServer; XDataServer: TXDataServer;
XDataServerForward: TSparkleForwardMiddleware;
XDataServerLogging: TSparkleGenericMiddleware; XDataServerLogging: TSparkleGenericMiddleware;
XDataServerCORS: TSparkleCorsMiddleware; XDataServerCORS: TSparkleCorsMiddleware;
XDataServerCompress: TSparkleCompressMiddleware; XDataServerCompress: TSparkleCompressMiddleware;
XDataServerJWT: TSparkleJwtMiddleware; XDataServerJWT: TSparkleJwtMiddleware;
procedure XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
procedure XDataServerLoggingMiddlewareCreate(Sender: TObject; procedure XDataServerLoggingMiddlewareCreate(Sender: TObject;
var Middleware: IHttpServerMiddleware); var Middleware: IHttpServerMiddleware);
procedure XDataServerJWTForbidRequest(Sender: TObject;
Context: THttpServerContext; var Forbid: Boolean);
procedure XDataServerJWTGetSecret(Sender: TObject; var Secret: string); procedure XDataServerJWTGetSecret(Sender: TObject; var Secret: string);
private private
{ Private declarations } { Private declarations }
...@@ -93,31 +93,15 @@ begin ...@@ -93,31 +93,15 @@ begin
Middleware := TLoggingMiddleware.Create(Logger); Middleware := TLoggingMiddleware.Create(Logger);
end; end;
procedure TApiServerModule.XDataServerJWTForbidRequest(Sender: TObject;
Context: THttpServerContext; var Forbid: Boolean);
var
Path: string;
begin
Path := Context.Request.Uri.Path;
if SameText(Context.Request.Method, 'OPTIONS') then
Forbid := False;
if Path.Contains('/swaggerui') then
Forbid := False;
if Path.Contains('/openapi/swagger.json') then
Forbid := False;
if Forbid then
Logger.Log(1, '[JWT] ForbidRequest fired (token missing/invalid/expired?)');
end;
procedure TApiServerModule.XDataServerJWTGetSecret(Sender: TObject; var Secret: procedure TApiServerModule.XDataServerJWTGetSecret(Sender: TObject; var Secret:
string); string);
begin begin
Secret := serverConfig.jwtTokenSecret; Secret := serverConfig.jwtTokenSecret;
end; end;
procedure TApiServerModule.XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
begin
Accept := True;
end;
end. end.
...@@ -4,6 +4,7 @@ interface ...@@ -4,6 +4,7 @@ interface
uses uses
XData.Service.Common, XData.Service.Common,
XData.Security.Attributes,
Aurelius.Mapping.Attributes, Aurelius.Mapping.Attributes,
System.Generics.Collections, System.Generics.Collections,
System.JSON; System.JSON;
...@@ -13,6 +14,7 @@ const ...@@ -13,6 +14,7 @@ const
type type
[ServiceContract, Model(API_MODEL)] [ServiceContract, Model(API_MODEL)]
[Authorize]
IApiService = interface(IInvokable) IApiService = interface(IInvokable)
['{793A44B7-2B00-4791-B249-97A681922D76}'] ['{793A44B7-2B00-4791-B249-97A681922D76}']
function TestApi(messageText: string): TJSONObject; function TestApi(messageText: string): TJSONObject;
......
...@@ -39,8 +39,13 @@ begin ...@@ -39,8 +39,13 @@ begin
on E: Exception do on E: Exception do
begin begin
Logger.Log(2, '--Error creating TApiDatabase: ' + E.Message); Logger.Log(2, '--Error creating TApiDatabase: ' + E.Message);
raise; raise EXDataHttpException.Create(500, 'Unable to connect to the database. Please contact support.');
end;
end; end;
if not FApiDatabase.ucDatabase.Connected then
begin
Logger.Log(1, 'Unable to connect to API database');
raise EXDataHttpException.Create(500, 'Unable to connect to the database. Please contact support.');
end; end;
end; end;
...@@ -69,6 +74,7 @@ function TApiService.TestApi(messageText: string): TJSONObject; ...@@ -69,6 +74,7 @@ function TApiService.TestApi(messageText: string): TJSONObject;
var var
requiredVersion: string; requiredVersion: string;
begin begin
try
Logger.Log(3, 'IApiService.TestApi called'); Logger.Log(3, 'IApiService.TestApi called');
Result := TJSONObject.Create; Result := TJSONObject.Create;
...@@ -80,10 +86,17 @@ begin ...@@ -80,10 +86,17 @@ begin
Result.AddPair('serverTime', DateTimeToStr(Now)); Result.AddPair('serverTime', DateTimeToStr(Now));
Result.AddPair('requiredWebClientVersion', requiredVersion); Result.AddPair('requiredWebClientVersion', requiredVersion);
Result.AddPair('note', 'If this endpoint is reachable, JWT auth passed. Version enforcement on every API call is a separate step (middleware).'); Result.AddPair('note', 'If this endpoint is reachable, JWT auth passed. Version enforcement on every API call is a separate step (middleware).');
except
on E: EXDataHttpException do
raise;
on E: Exception do
begin
Logger.Log(1, 'Test API failed: ' + E.ClassName + ': ' + E.Message);
raise EXDataHttpException.Create(500, 'Unable to complete the API test. Please contact support.');
end;
end;
end; end;
initialization initialization
RegisterServiceType(TApiService); RegisterServiceType(TApiService);
......
...@@ -6,7 +6,6 @@ object AppServerModule: TAppServerModule ...@@ -6,7 +6,6 @@ object AppServerModule: TAppServerModule
Top = 16 Top = 16
end end
object SparkleStaticServer: TSparkleStaticServer object SparkleStaticServer: TSparkleStaticServer
BaseUrl = 'http://localhost:2006/webPoliceReports/app/'
Dispatcher = SparkleHttpSysDispatcher Dispatcher = SparkleHttpSysDispatcher
Left = 88 Left = 88
Top = 88 Top = 88
......
...@@ -3,38 +3,32 @@ object AuthDatabase: TAuthDatabase ...@@ -3,38 +3,32 @@ object AuthDatabase: TAuthDatabase
OnDestroy = DataModuleDestroy OnDestroy = DataModuleDestroy
Height = 249 Height = 249
Width = 433 Width = 433
object ucHST: TUniConnection object ucDatabase: TUniConnection
ProviderName = 'MySQL' ProviderName = 'PostgreSQL'
Database = 'sleepdb' Port = 5432
Username = 'hstuser'
Server = '192.168.116.135'
LoginPrompt = False LoginPrompt = False
Left = 93 Left = 93
Top = 49 Top = 49
EncryptedPassword = '9AFF92FF8CFF86FF8CFFDEFFCFFFCEFF'
end end
object MySQLUniProvider1: TMySQLUniProvider object PostgreSQLUniProvider1: TPostgreSQLUniProvider
Left = 94 Left = 94
Top = 124 Top = 124
end end
object uqUser: TUniQuery object uqUser: TUniQuery
Connection = ucHST Connection = ucDatabase
SQL.Strings = ( SQL.Strings = (
'select * from users') 'select u.* from lems.users u'
'where upper(user_name) = :USER_NAME and u.dept = :AGENCY')
FetchRows = 100 FetchRows = 100
Left = 226 Left = 226
Top = 73 Top = 73
object uqUseruser_id: TIntegerField
FieldName = 'user_id'
end
object uqUseruser_name: TStringField
FieldName = 'user_name'
Required = True
end
object uqUseruser_password: TStringField
FieldName = 'user_password'
Required = True
Size = 64
end end
object uqAgencyConfig: TUniQuery
Connection = ucDatabase
SQL.Strings = (
'select agencyid, agencyname from lems.agency'
'where login = ''T'' order by agencyname')
Left = 320
Top = 73
end end
end end
...@@ -6,16 +6,14 @@ interface ...@@ -6,16 +6,14 @@ interface
uses uses
System.SysUtils, System.Classes, IniFiles, Vcl.Forms, MemDS, System.SysUtils, System.Classes, IniFiles, Vcl.Forms, MemDS,
Data.DB, DBAccess, Uni, UniProvider, PostgreSQLUniProvider, MySQLUniProvider; Data.DB, DBAccess, Uni, UniProvider, PostgreSQLUniProvider;
type type
TAuthDatabase = class(TDataModule) TAuthDatabase = class(TDataModule)
ucHST: TUniConnection; ucDatabase: TUniConnection;
MySQLUniProvider1: TMySQLUniProvider; PostgreSQLUniProvider1: TPostgreSQLUniProvider;
uqUser: TUniQuery; uqUser: TUniQuery;
uqUseruser_id: TIntegerField; uqAgencyConfig: TUniQuery;
uqUseruser_name: TStringField;
uqUseruser_password: TStringField;
procedure DataModuleCreate(Sender: TObject); procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject); procedure DataModuleDestroy(Sender: TObject);
private private
...@@ -44,12 +42,8 @@ procedure TAuthDatabase.DataModuleCreate(Sender: TObject); ...@@ -44,12 +42,8 @@ procedure TAuthDatabase.DataModuleCreate(Sender: TObject);
begin begin
Logger.Log(5, 'TAuthDatabase.DataModuleCreate'); Logger.Log(5, 'TAuthDatabase.DataModuleCreate');
try try
ucHST.Database := IniEntries.dbDatabase; IniEntries.ConfigureConnection(ucDatabase);
ucHST.Server := IniEntries.dbServer; ucDatabase.Connect;
ucHST.Port := IniEntries.dbPort;
ucHST.Username := IniEntries.dbUsername;
ucHST.Password := IniEntries.dbPassword;
ucHST.Connect;
except except
on E: Exception do on E: Exception do
begin begin
...@@ -61,7 +55,7 @@ end; ...@@ -61,7 +55,7 @@ end;
procedure TAuthDatabase.DataModuleDestroy(Sender: TObject); procedure TAuthDatabase.DataModuleDestroy(Sender: TObject);
begin begin
ucHST.Connected := false; ucDatabase.Connected := false;
end; end;
......
...@@ -15,6 +15,9 @@ object AuthServerModule: TAuthServerModule ...@@ -15,6 +15,9 @@ object AuthServerModule: TAuthServerModule
SwaggerUIOptions.TryItOutEnabled = True SwaggerUIOptions.TryItOutEnabled = True
Left = 91 Left = 91
Top = 92 Top = 92
object XDataServerForward: TSparkleForwardMiddleware
OnAcceptProxy = XDataServerForwardAcceptProxy
end
object XDataServerLogging: TSparkleGenericMiddleware object XDataServerLogging: TSparkleGenericMiddleware
OnMiddlewareCreate = XDataServerLoggingMiddlewareCreate OnMiddlewareCreate = XDataServerLoggingMiddlewareCreate
end end
......
...@@ -12,15 +12,17 @@ uses ...@@ -12,15 +12,17 @@ uses
Sparkle.Comp.Server, Sparkle.Comp.JwtMiddleware, XData.Comp.Server, Sparkle.Comp.Server, Sparkle.Comp.JwtMiddleware, XData.Comp.Server,
Sparkle.Comp.HttpSysDispatcher, Sparkle.Comp.CompressMiddleware, Sparkle.Comp.HttpSysDispatcher, Sparkle.Comp.CompressMiddleware,
Sparkle.Comp.CorsMiddleware, Sparkle.HttpServer.Module, Sparkle.Comp.CorsMiddleware, Sparkle.HttpServer.Module,
Sparkle.HttpServer.Context, Sparkle.Comp.GenericMiddleware; Sparkle.HttpServer.Context, Sparkle.Comp.GenericMiddleware, Sparkle.Comp.ForwardMiddleware;
type type
TAuthServerModule = class(TDataModule) TAuthServerModule = class(TDataModule)
SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher; SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher;
XDataServer: TXDataServer; XDataServer: TXDataServer;
XDataServerForward: TSparkleForwardMiddleware;
XDataServerLogging: TSparkleGenericMiddleware; XDataServerLogging: TSparkleGenericMiddleware;
XDataServerCORS: TSparkleCorsMiddleware; XDataServerCORS: TSparkleCorsMiddleware;
XDataServerCompress: TSparkleCompressMiddleware; XDataServerCompress: TSparkleCompressMiddleware;
procedure XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
procedure XDataServerLoggingMiddlewareCreate(Sender: TObject; procedure XDataServerLoggingMiddlewareCreate(Sender: TObject;
var Middleware: IHttpServerMiddleware); var Middleware: IHttpServerMiddleware);
private private
...@@ -76,4 +78,9 @@ begin ...@@ -76,4 +78,9 @@ begin
Middleware := TLoggingMiddleware.Create(Logger); Middleware := TLoggingMiddleware.Create(Logger);
end; end;
procedure TAuthServerModule.XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
begin
Accept := True;
end;
end. end.
...@@ -12,11 +12,25 @@ const ...@@ -12,11 +12,25 @@ const
AUTH_MODEL = 'Auth'; AUTH_MODEL = 'Auth';
type type
TAgencyConfigItem = class
public
id: string;
agency: string;
name: string;
end;
TAgencyConfigList = class
public
count: integer;
returned: integer;
data: TList<TAgencyConfigItem>;
end;
[ServiceContract, Model(AUTH_MODEL)] [ServiceContract, Model(AUTH_MODEL)]
IAuthService = interface(IInvokable) IAuthService = interface(IInvokable)
['{AA668BA0-3129-4B02-88BF-4089D45D9249}'] ['{AA668BA0-3129-4B02-88BF-4089D45D9249}']
[HttpPost]function Login(const username, password, clientVersion: string): string; [HttpPost]function Login(username, password, agency, clientVersion: string): string;
[HttpGet] function GetAgencyConfigList: TAgencyConfigList;
function VerifyVersion(clientVersion: string): TJSONObject; function VerifyVersion(clientVersion: string): TJSONObject;
end; end;
......
...@@ -3,8 +3,10 @@ unit Auth.ServiceImpl; ...@@ -3,8 +3,10 @@ unit Auth.ServiceImpl;
interface interface
uses uses
System.AnsiStrings,
System.SysUtils, System.SysUtils,
System.Classes, System.Classes,
System.Generics.Collections,
System.JSON, System.JSON,
System.IniFiles, System.IniFiles,
System.DateUtils, System.DateUtils,
...@@ -28,9 +30,10 @@ type ...@@ -28,9 +30,10 @@ type
strict private strict private
AuthDb: TAuthDatabase; AuthDb: TAuthDatabase;
function GetWebClientVersion: string; function GetWebClientVersion: string;
function Decrypt(inStr, keyStr: AnsiString): AnsiString;
public public
// Note: CHANGED - Login now takes a plain text password (kgOrders style) function Login(username, password, agency, clientVersion: string): string;
function Login(const username, password, clientVersion: string): string; function GetAgencyConfigList: TAgencyConfigList;
function VerifyVersion(clientVersion: string): TJSONObject; function VerifyVersion(clientVersion: string): TJSONObject;
procedure AfterConstruction; override; procedure AfterConstruction; override;
procedure BeforeDestruction; override; procedure BeforeDestruction; override;
...@@ -43,14 +46,21 @@ begin ...@@ -43,14 +46,21 @@ begin
inherited; inherited;
try try
AuthDb := TAuthDatabase.Create(nil); AuthDb := TAuthDatabase.Create(nil);
Logger.Log(5, 'TAuthService.AfterConstruction - AuthDb created');
except except
on E: Exception do on E: Exception do
begin begin
Logger.Log(1, 'Error creating AuthDb: ' + E.Message); Logger.Log(1, 'Error creating AuthDb: ' + E.Message);
raise EXDataHttpException.Create(500, 'Unable to create Auth database.'); FreeAndNil(AuthDb);
raise EXDataHttpException.Create(500, 'Unable to connect to the database. Please contact support.');
end;
end; end;
if not AuthDb.ucDatabase.Connected then
begin
Logger.Log(1, 'Unable to connect to auth database');
FreeAndNil(AuthDb);
raise EXDataHttpException.Create(500, 'Unable to connect to the database. Please contact support.');
end; end;
Logger.Log(5, 'TAuthService.AfterConstruction - AuthDb created');
end; end;
procedure TAuthService.BeforeDestruction; procedure TAuthService.BeforeDestruction;
...@@ -77,6 +87,7 @@ function TAuthService.VerifyVersion(clientVersion: string): TJSONObject; ...@@ -77,6 +87,7 @@ function TAuthService.VerifyVersion(clientVersion: string): TJSONObject;
var var
webClientVersion: string; webClientVersion: string;
begin begin
try
Logger.Log(5, 'TAuthService.VerifyVersion(clientVersion: ' + clientVersion + ')'); Logger.Log(5, 'TAuthService.VerifyVersion(clientVersion: ' + clientVersion + ')');
Result := TJSONObject.Create; Result := TJSONObject.Create;
...@@ -100,67 +111,135 @@ begin ...@@ -100,67 +111,135 @@ begin
' Server version: ' + webClientVersion + sLineBreak + ' Server version: ' + webClientVersion + sLineBreak +
'Please clear cache and reload.'); 'Please clear cache and reload.');
end; end;
except
on E: EXDataHttpException do
raise;
on E: Exception do
begin
Logger.Log(1, 'Version verification failed: ' + E.ClassName + ': ' + E.Message);
raise EXDataHttpException.Create(500, 'Unable to verify the application version. Please contact support.');
end;
end;
end; end;
function TAuthService.Login(username, password, agency, clientVersion: string): string;
function TAuthService.Login(const username, password, clientVersion: string): string;
var var
sql: string; passwordKey: AnsiString;
storedHash: string; decryptedPassword: string;
passwordHash: string;
webClientVersion: string;
jwt: TJWT; jwt: TJWT;
begin begin
Logger.Log(3, Format('AuthService.Login - User: "%s"', [username]));
try try
sql := 'select user_id, user_name, user_password from users where user_name = ' + QuotedStr(username) + ' limit 1'; Logger.Log(3, Format('AuthService.Login - User: "%s" Agency: "%s"', [username, agency]));
DoQuery(AuthDb.uqUser, sql); if (Trim(username) = '') or (Trim(password) = '') or (Trim(agency) = '') then
except raise EXDataHttpUnauthorized.Create('Username, password, and agency are required');
on E: Exception do
begin
Logger.Log(1, 'Login failed due to database error: ' + E.Message);
raise EXDataHttpException.Create(500, 'Login failed: Unable to connect to the database.');
end;
end;
try
AuthDb.uqUser.Close;
AuthDb.uqUser.ParamByName('USER_NAME').AsString := UpperCase(Trim(username));
AuthDb.uqUser.ParamByName('AGENCY').AsString := UpperCase(Trim(agency));
AuthDb.uqUser.Open;
if AuthDb.uqUser.IsEmpty then if AuthDb.uqUser.IsEmpty then
begin
Logger.Log(2, 'Login Error: Invalid username or password');
raise EXDataHttpUnauthorized.Create('Invalid username or password'); raise EXDataHttpUnauthorized.Create('Invalid username or password');
end; if AuthDb.uqUser.FieldByName('active').AsString = 'F' then
raise EXDataHttpUnauthorized.Create('User not active');
passwordHash := password.ToUpper;
storedHash := AuthDb.uqUser.FieldByName('user_password').AsString.ToUpper;
// passwordHash := THashSHA2.GetHashString(username + password, THashSHA2.TSHA2Version.SHA256).ToUpper;
// storedHash := AuthDb.uqUser.FieldByName('user_password').AsString.ToUpper;
if storedHash <> passwordHash then passwordKey := 'wx3cFo$kIf2jrk(gOmvi7uvPfk*iorE8@kfm+nvR6jfh=swDqalpokSjf';
begin decryptedPassword := UpperCase(Trim(string(Decrypt(AnsiString(AuthDb.uqUser.FieldByName('password').AsString), passwordKey))));
Logger.Log(2, 'Login Error: Invalid username or password'); if decryptedPassword <> UpperCase(Trim(password)) then
raise EXDataHttpUnauthorized.Create('Invalid username or password'); raise EXDataHttpUnauthorized.Create('Invalid username or password');
end;
webClientVersion := GetWebClientVersion;
jwt := TJWT.Create; jwt := TJWT.Create;
try try
jwt.Claims.JWTId := LowerCase(Copy(TUtils.GuidToVariant(TUtils.NewGuid), 2, 36)); jwt.Claims.JWTId := LowerCase(Copy(TUtils.GuidToVariant(TUtils.NewGuid), 2, 36));
jwt.Claims.IssuedAt := Now; jwt.Claims.IssuedAt := Now;
jwt.Claims.Expiration := IncHour(Now, 24); jwt.Claims.Expiration := IncHour(Now, 24);
jwt.Claims.SetClaimOfType<string>('user_id', AuthDb.uqUser.FieldByName('userid').AsString);
jwt.Claims.SetClaimOfType<Integer>('user_id', AuthDb.uqUser.FieldByName('user_id').AsInteger);
jwt.Claims.SetClaimOfType<string>('user_name', AuthDb.uqUser.FieldByName('user_name').AsString); jwt.Claims.SetClaimOfType<string>('user_name', AuthDb.uqUser.FieldByName('user_name').AsString);
jwt.Claims.SetClaimOfType<string>('user_fullname', AuthDb.uqUser.FieldByName('firstname').AsString + ' ' + AuthDb.uqUser.FieldByName('lastname').AsString);
jwt.Claims.SetClaimOfType<string>('user_agency', AuthDb.uqUser.FieldByName('dept').AsString);
jwt.Claims.SetClaimOfType<string>('user_badge', AuthDb.uqUser.FieldByName('badgenum').AsString);
jwt.Claims.SetClaimOfType<string>('user_personnelid', AuthDb.uqUser.FieldByName('personnelid').AsString);
jwt.Claims.SetClaimOfType<Boolean>('user_admin', SameText(Trim(username), 'admin'));
jwt.Claims.SetClaimOfType<string>('client_version', clientVersion); jwt.Claims.SetClaimOfType<string>('client_version', clientVersion);
jwt.Claims.SetClaimOfType<string>('server_version', webClientVersion); jwt.Claims.SetClaimOfType<string>('server_version', GetWebClientVersion);
Result := TJOSE.SHA256CompactToken(serverConfig.jwtTokenSecret, jwt); Result := TJOSE.SHA256CompactToken(serverConfig.jwtTokenSecret, jwt);
finally finally
jwt.Free; jwt.Free;
end; end;
finally
AuthDb.uqUser.Close;
end;
except
on E: EXDataHttpException do
begin
Logger.Log(2, 'Login failed: ' + E.Message);
raise;
end;
on E: Exception do
begin
Logger.Log(1, 'Login failed: ' + E.ClassName + ': ' + E.Message);
raise EXDataHttpException.Create(500, 'Unable to complete login. Please contact support.');
end;
end;
end;
function TAuthService.GetAgencyConfigList: TAgencyConfigList;
var
agencyConfig: TAgencyConfigItem;
begin
try
Result := TAgencyConfigList.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
Result.data := TList<TAgencyConfigItem>.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result.data);
try
AuthDb.uqAgencyConfig.Open;
while not AuthDb.uqAgencyConfig.Eof do
begin
agencyConfig := TAgencyConfigItem.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(agencyConfig);
Result.data.Add(agencyConfig);
agencyConfig.id := AuthDb.uqAgencyConfig.FieldByName('agencyid').AsString;
agencyConfig.agency := AuthDb.uqAgencyConfig.FieldByName('agencyid').AsString;
agencyConfig.name := AuthDb.uqAgencyConfig.FieldByName('agencyname').AsString;
AuthDb.uqAgencyConfig.Next;
end;
Result.count := Result.data.Count;
Result.returned := Result.data.Count;
finally
AuthDb.uqAgencyConfig.Close;
end;
except
on E: EXDataHttpException do
raise;
on E: Exception do
begin
Logger.Log(1, 'Agency lookup failed: ' + E.ClassName + ': ' + E.Message);
raise EXDataHttpException.Create(500, 'Unable to load agencies. Please contact support.');
end;
end;
end;
function TAuthService.Decrypt(inStr, keyStr: AnsiString): AnsiString;
var
outStr: AnsiString;
k, i: integer;
tempKeyStr: AnsiString;
begin
if inStr = '' then Exit('');
if keyStr = '' then Exit('');
k := Integer(inStr[1]);
tempKeyStr := keyStr;
while Length(tempKeyStr) < 256 do
tempKeyStr := tempKeyStr + tempKeyStr;
for i := 1 to Length(inStr) - 1 do
begin
k := (k + i) mod 256;
outStr := outStr + AnsiChar(Integer(inStr[i+1]) xor Integer(tempKeyStr[k+1]));
end;
Result := System.AnsiStrings.Trim(outStr);
end; end;
initialization initialization
......
...@@ -90,7 +90,9 @@ begin ...@@ -90,7 +90,9 @@ begin
Logger.Log(1, '--- Server Config Values ---'); Logger.Log(1, '--- Server Config Values ---');
Logger.Log(1, '-- url: ' + serverConfig.url + IfThen(serverConfig.url = defaultServerUrl, ' [default]', ' [from config]')); Logger.Log(1, '-- url: ' + serverConfig.url + IfThen(serverConfig.url = defaultServerUrl, ' [default]', ' [from config]'));
Logger.Log(1, '-- adminPassword: ' + serverConfig.adminPassword + IfThen(serverConfig.adminPassword = 'whatisthisusedfor', ' [default]', ' [from config]')); // Note: Uncomment the masked log below to hide the password instead.
// Logger.Log(1, '-- adminPassword: ' + IfThen(serverConfig.adminPassword <> '', '[configured]', '[not set]'));
Logger.Log(1, '-- adminPassword: ' + serverConfig.adminPassword);
Logger.Log(1, '-- jwtTokenSecret: [from config/default]'); Logger.Log(1, '-- jwtTokenSecret: [from config/default]');
Logger.Log(1, '-- webAppFolder: ' + serverConfig.webAppFolder + IfThen(serverConfig.webAppFolder = 'static', ' [default]', ' [from config]')); Logger.Log(1, '-- webAppFolder: ' + serverConfig.webAppFolder + IfThen(serverConfig.webAppFolder = 'static', ' [default]', ' [from config]'));
Logger.Log(1, '-- reportsFolder: ' + serverConfig.reportsFolder + IfThen(serverConfig.reportsFolder = 'static\reports\', ' [default]', ' [from config]')); Logger.Log(1, '-- reportsFolder: ' + serverConfig.reportsFolder + IfThen(serverConfig.reportsFolder = 'static\reports\', ' [default]', ' [from config]'));
......
...@@ -3,7 +3,7 @@ unit Common.Ini; ...@@ -3,7 +3,7 @@ unit Common.Ini;
interface interface
uses uses
System.SysUtils, System.IniFiles, Vcl.Forms; System.SysUtils, System.IniFiles, Vcl.Forms, Uni;
type type
TIniEntries = class TIniEntries = class
...@@ -21,6 +21,7 @@ type ...@@ -21,6 +21,7 @@ type
public public
constructor Create; constructor Create;
procedure ConfigureConnection(Connection: TUniConnection);
property consoleLogLevel: Integer read FConsoleLogLevel; property consoleLogLevel: Integer read FConsoleLogLevel;
property fileLogLevel: Integer read FFileLogLevel; property fileLogLevel: Integer read FFileLogLevel;
...@@ -60,16 +61,26 @@ begin ...@@ -60,16 +61,26 @@ begin
FFileLogLevel := iniFile.ReadInteger('Settings', 'FileLogLevel', 3); FFileLogLevel := iniFile.ReadInteger('Settings', 'FileLogLevel', 3);
FLogFileNum := iniFile.ReadInteger('Settings', 'LogFileNum', 0); FLogFileNum := iniFile.ReadInteger('Settings', 'LogFileNum', 0);
FDBServer := iniFile.ReadString('Database', 'Server', '192.168.116.129'); FDBServer := iniFile.ReadString('Postgres', 'Server', '');
FDBPort := iniFile.ReadInteger('Database', 'Port', 0); FDBPort := iniFile.ReadInteger('Postgres', 'Port', 5432);
FDBDatabase := iniFile.ReadString('Database', 'Database', 'kg_order_entry'); FDBDatabase := iniFile.ReadString('Postgres', 'Database', 'lems_wcso');
FDBUsername := iniFile.ReadString('Database', 'Username', 'root'); FDBUsername := iniFile.ReadString('Postgres', 'Username', 'postgres');
FDBPassword := iniFile.ReadString('Database', 'Password', 'emsys01'); FDBPassword := iniFile.ReadString('Postgres', 'Password', '');
finally finally
iniFile.Free; iniFile.Free;
end; end;
end; end;
end. procedure TIniEntries.ConfigureConnection(Connection: TUniConnection);
begin
Connection.ProviderName := 'PostgreSQL';
Connection.Server := FDBServer;
Connection.Port := FDBPort;
Connection.Database := FDBDatabase;
Connection.Username := FDBUsername;
Connection.Password := FDBPassword;
Connection.LoginPrompt := False;
end;
end.
//////// Log Levels /////////
// 1 - Startup Information
// 2 - Application/Database Connections
// 3 - Endpoints
// 4 - CHARMS Interactions
// 5 - Email Poller
unit Common.Logging; unit Common.Logging;
interface interface
......
...@@ -66,8 +66,16 @@ procedure TFMain.timerStartServerTimer(Sender: TObject); ...@@ -66,8 +66,16 @@ procedure TFMain.timerStartServerTimer(Sender: TObject);
begin begin
timerStartServer.Enabled := False; timerStartServer.Enabled := False;
Caption := Caption + ' ver ' + exeInfoVersion.FileVersion; Caption := Caption + ' ver ' + exeInfoVersion.FileVersion;
try
LoadIniEntries; LoadIniEntries;
LoadServerConfig; LoadServerConfig;
except
on E: Exception do
begin
Logger.Log(1, 'Server startup stopped: ' + E.Message);
Exit;
end;
end;
StartServers; StartServers;
end; end;
...@@ -87,12 +95,14 @@ begin ...@@ -87,12 +95,14 @@ begin
Logger.Log(1, '******************************************************'); Logger.Log(1, '******************************************************');
Logger.Log(1, ''); Logger.Log(1, '');
Logger.Log(1, '--- Database ---'); Logger.Log(1, '--- Postgres ---');
Logger.Log(1, '--Database->Server: ' + IniEntries.dbServer); Logger.Log(1, '--Postgres->Server: ' + IniEntries.dbServer);
Logger.Log(1, '--Database->Port: ' + IniEntries.dbPort.ToString); Logger.Log(1, '--Postgres->Port: ' + IniEntries.dbPort.ToString);
Logger.Log(1, '--Database->Database: ' + IniEntries.dbDatabase); Logger.Log(1, '--Postgres->Database: ' + IniEntries.dbDatabase);
Logger.Log(1, '--Database->Username: ' + IniEntries.dbUsername); Logger.Log(1, '--Postgres->Username: ' + IniEntries.dbUsername);
Logger.Log(1, '--Database->Password: ' + IniEntries.dbPassword); // Note: Uncomment the masked log below to hide the password instead.
// Logger.Log(1, '--Postgres->Password: ' + IfThen(IniEntries.dbPassword <> '', '[configured]', '[not set]'));
Logger.Log(1, '--Postgres->Password: ' + IniEntries.dbPassword);
Logger.Log(1, ''); Logger.Log(1, '');
Logger.Log(1, '--- Settings ---'); Logger.Log(1, '--- Settings ---');
......
...@@ -3,6 +3,7 @@ program templateXDataServer; ...@@ -3,6 +3,7 @@ program templateXDataServer;
uses uses
Vcl.Forms, Vcl.Forms,
FastMM4, FastMM4,
System.Classes,
System.SyncObjs, System.SyncObjs,
System.SysUtils, System.SysUtils,
Vcl.StdCtrls, Vcl.StdCtrls,
...@@ -69,6 +70,9 @@ var ...@@ -69,6 +70,9 @@ var
logTime: TDateTime; logTime: TDateTime;
formattedMessage: string; formattedMessage: string;
begin begin
if logLevel > FLogLevel then
Exit;
FCriticalSection.Acquire; FCriticalSection.Acquire;
try try
logTime := Now; logTime := Now;
...@@ -80,11 +84,16 @@ begin ...@@ -80,11 +84,16 @@ begin
else else
formattedMessage := formattedMessage + '[' + IntToStr(logLevel) + '] ' + logMsg; formattedMessage := formattedMessage + '[' + IntToStr(logLevel) + '] ' + logMsg;
if logLevel <= FLogLevel then
FLogMemo.Lines.Add(formattedMessage);
finally finally
FCriticalSection.Release; FCriticalSection.Release;
end; end;
TThread.Queue(nil,
procedure
begin
if Assigned(FLogMemo) and not (csDestroying in FLogMemo.ComponentState) then
FLogMemo.Lines.Add(formattedMessage);
end);
end; end;
{ TFileLogAppender } { TFileLogAppender }
......
...@@ -88,6 +88,10 @@ ...@@ -88,6 +88,10 @@
<VerInfo_Locale>1033</VerInfo_Locale> <VerInfo_Locale>1033</VerInfo_Locale>
<DCC_UnitSearchPath>C:\RADTOOLS\FastMM4;$(DCC_UnitSearchPath)</DCC_UnitSearchPath> <DCC_UnitSearchPath>C:\RADTOOLS\FastMM4;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
<DCC_ExeOutput>.\bin</DCC_ExeOutput> <DCC_ExeOutput>.\bin</DCC_ExeOutput>
<VerInfo_MajorVer>0</VerInfo_MajorVer>
<VerInfo_MinorVer>1</VerInfo_MinorVer>
<VerInfo_Release>1</VerInfo_Release>
<VerInfo_Keys>CompanyName=;FileDescription=$(MSBuildProjectName);FileVersion=0.1.1.0;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProgramID=com.embarcadero.$(MSBuildProjectName);ProductName=$(MSBuildProjectName);ProductVersion=1.0.0.0;Comments=</VerInfo_Keys>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Cfg_2)'!=''"> <PropertyGroup Condition="'$(Cfg_2)'!=''">
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols> <DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
...@@ -161,10 +165,10 @@ ...@@ -161,10 +165,10 @@
<Source Name="MainSource">templateXDataServer.dpr</Source> <Source Name="MainSource">templateXDataServer.dpr</Source>
</Source> </Source>
<Excluded_Packages> <Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcboffice2k290.bpl">Embarcadero C++Builder Office 2000 Servers Package</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\bcboffice2k370.bpl">Embarcadero C++Builder Office 2000 Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcbofficexp290.bpl">Embarcadero C++Builder Office XP Servers Package</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\bcbofficexp370.bpl">Embarcadero C++Builder Office XP Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dcloffice2k290.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\dcloffice2k370.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dclofficexp290.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages> <Excluded_Packages Name="$(BDSBIN)\dclofficexp370.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages>
</Excluded_Packages> </Excluded_Packages>
</Delphi.Personality> </Delphi.Personality>
<Deployment Version="5"> <Deployment Version="5">
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment