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
implementation
uses
View.ErrorPage;
procedure LoadConfig(LoadProc: TConfigLoadedProc);
procedure OnSuccess(Response: IHttpResponse);
......@@ -36,18 +39,23 @@ procedure LoadConfig(LoadProc: TConfigLoadedProc);
begin
Config := TAppConfig.Create;
try
if Response.StatusCode = 200 then
begin
Obj := TJSObject(TJSJSON.parse(Response.ContentAsText));
try
if Response.StatusCode = 200 then
begin
Obj := TJSObject(TJSJSON.parse(Response.ContentAsText));
if JS.toString(Obj['AuthUrl']) <> '' then
Config.AuthUrl := JS.toString(Obj['AuthUrl']);
if Obj.HasOwnProperty('AuthUrl') and (JS.toString(Obj['AuthUrl']) <> '') then
Config.AuthUrl := JS.toString(Obj['AuthUrl']);
if JS.toString(Obj['ApiUrl']) <> '' then
Config.ApiUrl := JS.toString(Obj['ApiUrl']);
if Obj.HasOwnProperty('ApiUrl') and (JS.toString(Obj['ApiUrl']) <> '') then
Config.ApiUrl := JS.toString(Obj['ApiUrl']);
end;
except
TFViewErrorPage.Display('Unable to read config/config.json. Please correct the configuration JSON and reload the application.');
Exit;
end;
finally
LoadProc(Config);
finally
Config.Free;
end;
end;
......
......@@ -23,7 +23,7 @@ type
public
constructor Create; reintroduce;
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 Logout;
function GetToken: string;
......@@ -72,7 +72,7 @@ end;
constructor TAuthService.Create;
begin
FClient := TXDataWebClient.Create(nil);
FClient.Connection := DMConnection.AuthConnection;
FClient.Connection := dmConnection.authConnection;
end;
procedure TAuthService.DeleteToken;
......@@ -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);
procedure OnLoad(Response: TXDataClientResponse);
......@@ -141,14 +141,14 @@ procedure TAuthService.Login(AUser, APassword, AClientVersion: string; ASuccess:
end;
begin
if (AUser = '') or (APassword = '') then
if (AUser = '') or (APassword = '') or (AAgency = '') then
begin
AError('Please enter a username and a password');
AError('Please enter a username, password, and agency');
Exit;
end;
FClient.RawInvoke(
'IAuthService.Login', [AUser, APassword, AClientVersion],
'IAuthService.Login', [AUser, APassword, AAgency, AClientVersion],
@OnLoad, @OnError
);
end;
......@@ -189,7 +189,13 @@ function TAuthService.TokenExpired: Boolean;
begin
if not Authenticated then
Exit(False);
Result := TJwtHelper.TokenExpired(GetToken);
try
Result := TJwtHelper.TokenExpired(GetToken);
except
Result := True;
end;
if Result then
DeleteToken;
end;
function TAuthService.TokenPayload: JS.TJSObject;
......@@ -243,7 +249,7 @@ end;
class function TJwtHelper.TokenExpired(AToken: string): Boolean;
begin
if not HasExpirationDate(AToken) then
Exit(False);
Exit(True);
Result := TJSDate.now > toInteger(TokenExpirationDate(AToken).valueOf);
end;
......
object DMConnection: TDMConnection
Height = 264
Width = 395
object ApiConnection: TXDataWebConnection
URL = 'http://localhost:2004/emsys/template/api'
OnError = ApiConnectionError
OnRequest = ApiConnectionRequest
OnResponse = ApiConnectionResponse
object apiConnection: TXDataWebConnection
URL = 'http://localhost:2001/emsys/template/api'
OnError = apiConnectionError
OnRequest = apiConnectionRequest
OnResponse = apiConnectionResponse
Left = 48
Top = 80
end
object AuthConnection: TXDataWebConnection
URL = 'http://localhost:2004/emsys/template/auth'
OnError = AuthConnectionError
object authConnection: TXDataWebConnection
URL = 'http://localhost:2001/emsys/template/auth'
OnError = authConnectionError
Left = 48
Top = 16
end
......
......@@ -8,23 +8,23 @@ uses
type
TDMConnection = class(TWebDataModule)
ApiConnection: TXDataWebConnection;
AuthConnection: TXDataWebConnection;
procedure ApiConnectionError(Error: TXDataWebConnectionError);
procedure ApiConnectionRequest(Args: TXDataWebConnectionRequest);
procedure ApiConnectionResponse(Args: TXDataWebConnectionResponse);
procedure AuthConnectionError(Error: TXDataWebConnectionError);
apiConnection: TXDataWebConnection;
authConnection: TXDataWebConnection;
procedure apiConnectionError(Error: TXDataWebConnectionError);
procedure apiConnectionRequest(Args: TXDataWebConnectionRequest);
procedure apiConnectionResponse(Args: TXDataWebConnectionResponse);
procedure authConnectionError(Error: TXDataWebConnectionError);
private
FUnauthorizedAccessProc: TUnauthorizedAccessProc;
public
const clientVersion = '0.0.1';
const clientVersion = '0.1.1.0';
procedure InitApp(SuccessProc: TSuccessProc;
UnauthorizedAccessProc: TUnauthorizedAccessProc);
end;
var
DMConnection: TDMConnection;
dmConnection: TDMConnection;
implementation
......@@ -32,70 +32,52 @@ uses
JS, Web,
XData.Web.Request,
XData.Web.Response,
Auth.Service;
Auth.Service, View.ErrorPage;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TDMConnection.ApiConnectionError(Error: TXDataWebConnectionError);
var
errorMsg: string;
procedure TDMConnection.apiConnectionError(Error: TXDataWebConnectionError);
begin
errorMsg := Error.ErrorMessage;
if errorMsg = '' then
errorMsg := 'Connection error';
if Assigned(FUnauthorizedAccessProc) then
FUnauthorizedAccessProc(errorMsg)
else
ShowMessage(errorMsg);
TFViewErrorPage.DisplayConnectionError(Error);
end;
procedure TDMConnection.ApiConnectionRequest(Args: TXDataWebConnectionRequest);
procedure TDMConnection.apiConnectionRequest(Args: TXDataWebConnectionRequest);
begin
if AuthService.Authenticated then
Args.Request.Headers.SetValue('Authorization', 'Bearer ' + AuthService.GetToken);
end;
procedure TDMConnection.ApiConnectionResponse(
procedure TDMConnection.apiConnectionResponse(
Args: TXDataWebConnectionResponse);
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]));
end;
procedure TDMConnection.AuthConnectionError(Error: TXDataWebConnectionError);
var
errorMsg: string;
procedure TDMConnection.authConnectionError(Error: TXDataWebConnectionError);
begin
errorMsg := Error.ErrorMessage;
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);
TFViewErrorPage.DisplayConnectionError(Error);
end;
procedure TDMConnection.InitApp(SuccessProc: TSuccessProc;
UnauthorizedAccessProc: TUnauthorizedAccessProc);
procedure ConfigLoaded(Config: TAppConfig);
begin
if Config.AuthUrl <> '' then
AuthConnection.URL := Config.AuthUrl;
authConnection.URL := Config.AuthUrl;
if Config.ApiUrl <> '' then
ApiConnection.URL := Config.ApiUrl;
apiConnection.URL := Config.ApiUrl;
AuthConnection.Open(SuccessProc);
authConnection.Open(SuccessProc);
end;
begin
......
......@@ -12,11 +12,9 @@ procedure HideSpinner(SpinnerID: string);
procedure ShowErrorModal(msg: string);
function CalculateAge(DateOfBirth: TDateTime): Integer;
function FormatPhoneNumber(PhoneNumber: string): string;
procedure ApplyReportTitle(CurrentReportType: string);
procedure ShowToast(const MessageText: string; const ToastType: string = 'success');
procedure ShowConfirmationModal(msg, leftLabel, rightLabel: string; ConfirmProc: TProc<Boolean>);
procedure ShowNotificationModal(msg: string);
procedure ShowVersionMismatchAndReload(const ErrorText, ClientVersion: string);
implementation
......@@ -97,8 +95,8 @@ end;
procedure ShowErrorModal(msg: string);
begin
asm
var modal = document.getElementById('main_errormodal');
var label = document.getElementById('main_lblmodal_body');
var modal = document.getElementById('mdl_error');
var label = document.getElementById('lbl_modal_body');
var reloadBtn = document.getElementById('btn_modal_restart');
if (label) label.innerText = msg;
......@@ -125,8 +123,8 @@ end;
procedure ShowNotificationModal(msg: string);
begin
asm
var modal = document.getElementById('main_notification_modal');
var label = document.getElementById('main_notification_modal_body');
var modal = document.getElementById('mdl_notification');
var label = document.getElementById('lbl_notification_body');
var closeBtn = document.getElementById('btn_modal_close');
if (label) label.innerText = msg;
......@@ -153,33 +151,12 @@ begin
end;
// ShowConfirmationModal displays a two-button modal with custom labels.
// 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();
// Note: The callback is True when the right (confirm) button is clicked.
procedure ShowConfirmationModal(msg, leftLabel, rightLabel: string; ConfirmProc: TProc<Boolean>);
begin
asm
var modal = document.getElementById('main_confirmation_modal');
var body = document.getElementById('main_modal_body');
var modal = document.getElementById('mdl_confirmation');
var body = document.getElementById('lbl_confirmation_body');
var btnLeft = document.getElementById('btn_confirm_left');
var btnRight = document.getElementById('btn_confirm_right');
var bsModal;
......@@ -197,12 +174,12 @@ begin
btnLeft.onclick = function () {
bsModal.hide();
ConfirmProc(true); // user confirmed
ConfirmProc(false);
};
btnRight.onclick = function () {
bsModal.hide();
ConfirmProc(false); // user canceled
ConfirmProc(true);
};
bsModal = new bootstrap.Modal(modal, { keyboard: false });
......@@ -280,8 +257,8 @@ begin
end;
asm
var toastEl = document.getElementById('bootstrapToast');
var toastBody = document.getElementById('bootstrapToastBody');
var toastEl = document.getElementById('toast_bootstrap');
var toastBody = document.getElementById('lbl_bootstrap_toast_body');
if (!toastEl || !toastBody) return;
......@@ -318,55 +295,6 @@ begin
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.
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
Height = 764
CSSLibrary = cssBootstrap
......@@ -91,6 +91,17 @@ object FViewLogin: TFViewLogin
TextHint = 'Password'
WidthPercent = 100.000000000000000000
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
Left = 240
Top = 190
......@@ -107,7 +118,7 @@ object FViewLogin: TFViewLogin
HeightPercent = 100.000000000000000000
ParentFont = False
Role = 'null'
TabOrder = 2
TabOrder = 3
WidthPercent = 100.000000000000000000
OnClick = btnLoginClick
end
......@@ -125,7 +136,7 @@ object FViewLogin: TFViewLogin
Font.Style = []
ParentFont = False
Role = 'null'
TabOrder = 3
TabOrder = 4
Visible = False
object lblMessage: TWebLabel
Left = 16
......@@ -150,7 +161,7 @@ object FViewLogin: TFViewLogin
end
end
object xdwcLogin: TXDataWebClient
Connection = DMConnection.AuthConnection
Connection = dmConnection.authConnection
Left = 492
Top = 102
end
......
......@@ -22,6 +22,10 @@
</div>
<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>
</div>
......
......@@ -14,6 +14,7 @@ type
edtUsername: TWebEdit;
edtPassword: TWebEdit;
btnLogin: TWebButton;
lucbAgency: TWebLookupComboBox;
pnlMessage: TWebPanel;
lblMessage: TWebLabel;
btnCloseNotification: TWebButton;
......@@ -28,13 +29,14 @@ type
FMessage: string;
procedure ShowNotification(Notification: string);
procedure HideNotification;
procedure GetAgencyConfigList;
public
class procedure Display(LoginProc: TSuccessProc); overload;
class procedure Display(LoginProc: TSuccessProc; AMsg: string); overload;
end;
var
FViewLogin: TFViewLogin;
fViewLogin: TFViewLogin;
implementation
......@@ -58,15 +60,15 @@ procedure TFViewLogin.btnLoginClick(Sender: TObject);
procedure AuthConnectionOpened;
begin
AuthService.Login(
edtUsername.Text, edtPassword.Text, DMConnection.clientVersion,
edtUsername.Text, edtPassword.Text, lucbAgency.Value, dmConnection.clientVersion,
@LoginSuccess,
@LoginError
);
end;
begin
if not DMConnection.AuthConnection.Connected then
DMConnection.AuthConnection.Open(@AuthConnectionOpened)
if not dmConnection.authConnection.Connected then
dmConnection.authConnection.Open(@AuthConnectionOpened)
else
AuthConnectionOpened;
end;
......@@ -84,10 +86,10 @@ class procedure TFViewLogin.Display(LoginProc: TSuccessProc; AMsg: string);
end;
begin
if Assigned(FViewLogin) then
FViewLogin.Free;
FViewLogin := TFViewLogin.CreateNew(@FormCreate);
FViewLogin.FLoginProc := LoginProc;
if Assigned(fViewLogin) then
fViewLogin.Free;
fViewLogin := TFViewLogin.CreateNew(@FormCreate);
fViewLogin.FLoginProc := LoginProc;
end;
procedure TFViewLogin.HideNotification;
......@@ -113,8 +115,8 @@ end;
procedure TFViewLogin.WebFormShow(Sender: TObject);
begin
console.log(DMConnection.clientVersion);
FViewLogin.lblClientVersion.Caption := 'v' + DMConnection.clientVersion;
GetAgencyConfigList;
fViewLogin.lblClientVersion.Caption := 'v' + dmConnection.clientVersion;
if FMessage <> '' then
ShowNotification(FMessage)
else
......@@ -122,4 +124,34 @@ begin
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.
object FViewMain: TFViewMain
object fViewMain: TFViewMain
Width = 1322
Height = 764
CSSLibrary = cssBootstrap
......@@ -22,16 +22,6 @@ object FViewMain: TFViewMain
Transparent = False
WidthPercent = 100.000000000000000000
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
Left = 547
Top = 55
......@@ -51,6 +41,7 @@ object FViewMain: TFViewMain
ElementID = 'lbl_home'
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = lblHomeClick
Caption = 'Home'
end
object lblAppTitle: TWebLabel
......@@ -58,7 +49,7 @@ object FViewMain: TFViewMain
Top = 33
Width = 42
Height = 14
Caption = 'App Title'
Caption = 'EM Systems Template App'
ElementID = 'lbl_app_title'
ElementPosition = epRelative
HeightPercent = 100.000000000000000000
......@@ -117,7 +108,7 @@ object FViewMain: TFViewMain
WidthPercent = 100.000000000000000000
end
object xdwcMain: TXDataWebClient
Connection = DMConnection.ApiConnection
Connection = dmConnection.apiConnection
Left = 114
Top = 230
end
......
......@@ -2,7 +2,7 @@
<nav class="navbar navbar-expand-lg bg-body-tertiary border-bottom shadow-sm">
<div class="container-fluid">
<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>
</div>
......@@ -21,11 +21,6 @@
<i class="fa fa-home fa-fw"></i><span>Home</span>
</a>
</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>
<a class="dropdown-item d-flex align-items-center gap-2 text-danger" id="lbl_logout" href="#">
......@@ -88,7 +83,7 @@
Please contact EMSystems to solve the issue.
</div>
<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>
......
......@@ -12,7 +12,6 @@ type
TFViewMain = class(TWebForm)
pnlMain: TWebPanel;
lblUsername: TWebLabel;
lblUserProfile: TWebLinkLabel;
lblHome: TWebLinkLabel;
lblLogout: TWebLinkLabel;
lblVersion: TWebLabel;
......@@ -21,16 +20,18 @@ type
xdwcMain: TXDataWebClient;
procedure WebFormCreate(Sender: TObject);
procedure lblLogoutClick(Sender: TObject);
procedure lblHomeClick(Sender: TObject);
private
FChildForm: TWebForm;
FLogoutProc: TLogoutProc;
procedure ShowForm(aFormClass: TWebFormClass);
public
destructor Destroy; override;
class procedure Display(logoutProc: TLogoutProc);
end;
var
FViewMain: TFViewMain;
fViewMain: TFViewMain;
implementation
......@@ -46,11 +47,23 @@ var
begin
userName := JS.toString(AuthService.TokenPayload.Properties['user_name']);
lblUsername.Caption := userName;
lblVersion.Caption := 'v' + DMConnection.clientVersion;
lblVersion.Caption := 'v' + dmConnection.clientVersion;
ShowForm(TFTest);
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);
begin
if Assigned(FLogoutProc) then
......@@ -66,10 +79,10 @@ end;
class procedure TFViewMain.Display(logoutProc: TLogoutProc);
begin
if Assigned(FViewMain) then
FViewMain.Free;
FViewMain := TFViewMain.CreateNew;
FViewMain.FLogoutProc := logoutProc;
if Assigned(fViewMain) then
fViewMain.Free;
fViewMain := TFViewMain.CreateNew;
fViewMain.FLogoutProc := logoutProc;
end;
end.
......
object FTest: TFTest
object fTest: TFTest
Width = 640
Height = 480
CSSLibrary = cssBootstrap
......@@ -47,7 +47,7 @@ object FTest: TFTest
OnChange = memoTestDebugChange
end
object xdwcTest: TXDataWebClient
Connection = DMConnection.ApiConnection
Connection = dmConnection.apiConnection
Left = 464
Top = 208
end
......
......@@ -23,12 +23,12 @@ type
end;
var
FTest: TFTest;
fTest: TFTest;
implementation
uses
Auth.Service;
Auth.Service, Utils;
procedure TFTest.AddLine(const s: string);
begin
......@@ -71,57 +71,51 @@ var
messageText: string;
requiredVersion: string;
begin
memoTestDebug.Visible := True;
memoTestDebug.Lines.Clear;
try
memoTestDebug.Visible := True;
memoTestDebug.Lines.Clear;
AddLine('--- request ---');
AddLine('api url: ' + DMConnection.ApiConnection.URL);
AddLine('auth url: ' + DMConnection.AuthConnection.URL);
AddLine('clientVersion const: ' + DMConnection.clientVersion);
AddLine('--- request ---');
AddLine('api url: ' + dmConnection.apiConnection.URL);
AddLine('auth url: ' + dmConnection.authConnection.URL);
AddLine('clientVersion const: ' + dmConnection.clientVersion);
AddLine('');
AddLine('--- token / claims ---');
DumpClaims;
AddLine('');
AddLine('--- token / claims ---');
DumpClaims;
messageText := 'hello from TFTest @ ' + DateTimeToStr(Now);
messageText := 'hello from TFTest @ ' + DateTimeToStr(Now);
AddLine('');
AddLine('calling IApiService.TestApi ...');
try
AddLine('');
AddLine('calling IApiService.TestApi ...');
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('--- api response ---');
AddLine('');
AddLine('--- api response ---');
if not Assigned(response.Result) then
begin
AddLine('response.Result is nil');
Exit;
end;
if not Assigned(response.Result) then
raise Exception.Create('The server returned an empty API response.');
resultObj := TJSObject(response.Result);
resultObj := TJSObject(response.Result);
AddLine('messageEcho: ' + JS.toString(resultObj['messageEcho']));
AddLine('serverTime: ' + JS.toString(resultObj['serverTime']));
AddLine('requiredWebClientVersion: ' + JS.toString(resultObj['requiredWebClientVersion']));
AddLine('note: ' + JS.toString(resultObj['note']));
AddLine('messageEcho: ' + JS.toString(resultObj['messageEcho']));
AddLine('serverTime: ' + JS.toString(resultObj['serverTime']));
AddLine('requiredWebClientVersion: ' + JS.toString(resultObj['requiredWebClientVersion']));
AddLine('note: ' + JS.toString(resultObj['note']));
requiredVersion := JS.toString(resultObj['requiredWebClientVersion']);
requiredVersion := JS.toString(resultObj['requiredWebClientVersion']);
AddLine('');
AddLine('--- version compare (client-side) ---');
AddLine('clientVersion const: ' + DMConnection.clientVersion);
AddLine('requiredWebClientVersion: ' + requiredVersion);
AddLine('match: ' + BoolToStr(DMConnection.clientVersion = requiredVersion, True));
AddLine('');
AddLine('--- version compare (client-side) ---');
AddLine('clientVersion const: ' + dmConnection.clientVersion);
AddLine('requiredWebClientVersion: ' + requiredVersion);
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;
procedure TFTest.memoTestDebugChange(Sender: TObject);
......
......@@ -2,16 +2,18 @@ program templateWebApp;
uses
Vcl.Forms,
System.SysUtils,
XData.Web.Connection,
WEBLib.Dialogs,
Auth.Service in 'Auth.Service.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',
View.Main in 'View.Main.pas' {FViewMain: TWebForm} {*.html},
View.Main in 'View.Main.pas' {fViewMain: TWebForm} {*.html},
Utils in 'Utils.pas',
View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html},
View.Test in 'View.Test.pas' {FTest: TWebForm} {*.html};
View.Login in 'View.Login.pas' {fViewLogin: TWebForm} {*.html},
View.Test in 'View.Test.pas' {fTest: TWebForm} {*.html},
View.ErrorPage in 'View.ErrorPage.pas' {fViewErrorPage: TWebForm} {*.html};
{$R *.res}
......@@ -21,14 +23,14 @@ procedure DisplayMainView;
procedure ConnectProc;
begin
if Assigned(FViewLogin) then
FViewLogin.Free;
if Assigned(fViewLogin) then
FreeAndNil(fViewLogin);
TFViewMain.Display(@DisplayLoginView);
end;
begin
if not DMConnection.ApiConnection.Connected then
DMConnection.ApiConnection.Open(@ConnectProc)
if not dmConnection.apiConnection.Connected then
dmConnection.apiConnection.Open(@ConnectProc)
else
ConnectProc;
end;
......@@ -36,9 +38,9 @@ end;
procedure DisplayLoginView(AMessage: string = '');
begin
AuthService.Logout;
DMConnection.ApiConnection.Connected := False;
if Assigned(FViewMain) then
FViewMain.Free;
dmConnection.apiConnection.Connected := False;
if Assigned(fViewMain) then
fViewMain.Free;
TFViewLogin.Display(@DisplayMainView, AMessage);
end;
......@@ -51,7 +53,7 @@ procedure AfterVerifyClientVersion(Success: Boolean; Error: string);
begin
if not Success then
begin
ShowVersionMismatchAndReload(Error, DMConnection.clientVersion);
TFViewErrorPage.Display(Error + sLineBreak + sLineBreak + 'Current client version: v' + dmConnection.clientVersion);
Exit;
end;
......@@ -63,14 +65,14 @@ end;
procedure StartApplication;
begin
AuthService.VerifyClientVersion(DMConnection.clientVersion, @AfterVerifyClientVersion);
AuthService.VerifyClientVersion(dmConnection.clientVersion, @AfterVerifyClientVersion);
end;
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TDMConnection, DMConnection);
Application.CreateForm(TdmConnection, dmConnection);
Application.Run;
DMConnection.InitApp(@StartApplication, @UnauthorizedAccessProc);
dmConnection.InitApp(@StartApplication, @UnauthorizedAccessProc);
end.
......@@ -94,11 +94,11 @@
<DCC_RemoteDebug>false</DCC_RemoteDebug>
<VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>
<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>
<VerInfo_MajorVer>0</VerInfo_MajorVer>
<VerInfo_MinorVer>9</VerInfo_MinorVer>
<VerInfo_Release>8</VerInfo_Release>
<VerInfo_MinorVer>1</VerInfo_MinorVer>
<VerInfo_Release>1</VerInfo_Release>
<TMSWebBrowser>1</TMSWebBrowser>
<TMSUseJSDebugger>2</TMSUseJSDebugger>
<TMSWebSingleInstance>1</TMSWebSingleInstance>
......@@ -126,23 +126,28 @@
<DCCReference Include="Auth.Service.pas"/>
<DCCReference Include="App.Types.pas"/>
<DCCReference Include="ConnectionModule.pas">
<Form>DMConnection</Form>
<Form>dmConnection</Form>
<DesignClass>TWebDataModule</DesignClass>
</DCCReference>
<DCCReference Include="App.Config.pas"/>
<DCCReference Include="View.Main.pas">
<Form>FViewMain</Form>
<Form>fViewMain</Form>
<FormType>dfm</FormType>
<DesignClass>TWebForm</DesignClass>
</DCCReference>
<DCCReference Include="Utils.pas"/>
<DCCReference Include="View.Login.pas">
<Form>FViewLogin</Form>
<Form>fViewLogin</Form>
<FormType>dfm</FormType>
<DesignClass>TWebForm</DesignClass>
</DCCReference>
<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>
<DesignClass>TWebForm</DesignClass>
</DCCReference>
......@@ -171,10 +176,10 @@
<Source Name="MainSource">templateWebApp.dpr</Source>
</Source>
<Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcboffice2k290.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)\dcloffice2k290.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)\bcboffice2k370.bpl">Embarcadero C++Builder Office 2000 Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcbofficexp370.bpl">Embarcadero C++Builder Office XP Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dcloffice2k370.bpl">Microsoft Office 2000 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>
</Delphi.Personality>
<Deployment Version="5">
......
[Settings]
MemoLogLevel=5
FileLogLevel=5
LogFileNum=44
LogFileNum=47
DevMode=0
webClientVersion=0.0.1
webClientVersion=0.1.1.0
[Database]
--Server=192.168.116.129
Server=192.168.102.131
--Port=
Database=sleepdb
--Username=
--Password=
[Postgres]
Server=192.168.102.10
Port=5432
Database=lems_wcso
Username=postgres
Password=emsys01
[SMTP]
--Type=useExplicitTLS
......
......@@ -3,29 +3,30 @@ object ApiDatabase: TApiDatabase
Height = 358
Width = 519
object UniQuery1: TUniQuery
Connection = ucDatabase
SQL.Strings = (
'')
Left = 73
Top = 148
end
object MySQLUniProvider1: TMySQLUniProvider
object PostgreSQLUniProvider1: TPostgreSQLUniProvider
Left = 202
Top = 60
end
object UniQuery2: TUniQuery
Connection = ucDatabase
SQL.Strings = (
'')
Left = 179
Top = 148
end
object ucHST: TUniConnection
ProviderName = 'MySQL'
Database = 'sleepdb'
Username = 'hstuser'
Server = '192.168.116.135'
object ucDatabase: TUniConnection
ProviderName = 'PostgreSQL'
Port = 5432
SpecificOptions.Strings = (
'PostgreSQL.Schema=lems, avl, entcad')
LoginPrompt = False
Left = 81
Top = 59
EncryptedPassword = '9AFF92FF8CFF86FF8CFFDEFFCFFFCEFF'
end
end
......@@ -5,14 +5,14 @@ interface
uses
System.SysUtils, System.Classes, Data.DB, MemDS, DBAccess, Uni, UniProvider,
PostgreSQLUniProvider, System.Variants, System.Generics.Collections, System.IniFiles,
Common.Logging, Vcl.Forms, MySQLUniProvider, Common.Ini;
Common.Logging, Vcl.Forms, Common.Ini;
type
TApiDatabase = class(TDataModule)
UniQuery1: TUniQuery;
MySQLUniProvider1: TMySQLUniProvider;
PostgreSQLUniProvider1: TPostgreSQLUniProvider;
UniQuery2: TUniQuery;
ucHST: TUniConnection;
ucDatabase: TUniConnection;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
......@@ -36,16 +36,13 @@ procedure TApiDatabase.DataModuleCreate(Sender: TObject);
begin
Logger.Log(5, 'TApiDatabase.DataModuleCreate');
try
ucHST.Database := IniEntries.dbDatabase;
ucHST.Server := IniEntries.dbServer;
ucHST.Port := IniEntries.dbPort;
ucHST.Username := IniEntries.dbUsername;
ucHST.Password := IniEntries.dbPassword;
ucHST.Connect;
IniEntries.ConfigureConnection(ucDatabase);
ucDatabase.Connect;
ucDatabase.ExecSQL('set search_path to lems, avl, entcad, public');
except
on E: Exception do
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;
......
......@@ -16,6 +16,9 @@ object ApiServerModule: TApiServerModule
SwaggerUIOptions.TryItOutEnabled = True
Left = 89
Top = 112
object XDataServerForward: TSparkleForwardMiddleware
OnAcceptProxy = XDataServerForwardAcceptProxy
end
object XDataServerLogging: TSparkleGenericMiddleware
OnMiddlewareCreate = XDataServerLoggingMiddlewareCreate
end
......@@ -24,9 +27,8 @@ object ApiServerModule: TApiServerModule
object XDataServerCompress: TSparkleCompressMiddleware
end
object XDataServerJWT: TSparkleJwtMiddleware
ForbidAnonymousAccess = True
ForbidAnonymousAccess = False
OnGetSecret = XDataServerJWTGetSecret
OnForbidRequest = XDataServerJWTForbidRequest
end
end
end
......@@ -15,20 +15,20 @@ uses
Sparkle.HttpServer.Module, Sparkle.HttpServer.Context,
Sparkle.Comp.CompressMiddleware, Sparkle.Comp.CorsMiddleware,
Sparkle.Comp.GenericMiddleware, Aurelius.Drivers.UniDac, UniProvider,
Data.DB, DBAccess, Uni;
Data.DB, DBAccess, Uni, Sparkle.Comp.ForwardMiddleware;
type
TApiServerModule = class(TDataModule)
SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher;
XDataServer: TXDataServer;
XDataServerForward: TSparkleForwardMiddleware;
XDataServerLogging: TSparkleGenericMiddleware;
XDataServerCORS: TSparkleCorsMiddleware;
XDataServerCompress: TSparkleCompressMiddleware;
XDataServerJWT: TSparkleJwtMiddleware;
procedure XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
procedure XDataServerLoggingMiddlewareCreate(Sender: TObject;
var Middleware: IHttpServerMiddleware);
procedure XDataServerJWTForbidRequest(Sender: TObject;
Context: THttpServerContext; var Forbid: Boolean);
procedure XDataServerJWTGetSecret(Sender: TObject; var Secret: string);
private
{ Private declarations }
......@@ -93,31 +93,15 @@ begin
Middleware := TLoggingMiddleware.Create(Logger);
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:
string);
begin
Secret := serverConfig.jwtTokenSecret;
end;
procedure TApiServerModule.XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
begin
Accept := True;
end;
end.
......@@ -4,6 +4,7 @@ interface
uses
XData.Service.Common,
XData.Security.Attributes,
Aurelius.Mapping.Attributes,
System.Generics.Collections,
System.JSON;
......@@ -13,6 +14,7 @@ const
type
[ServiceContract, Model(API_MODEL)]
[Authorize]
IApiService = interface(IInvokable)
['{793A44B7-2B00-4791-B249-97A681922D76}']
function TestApi(messageText: string): TJSONObject;
......
......@@ -39,9 +39,14 @@ begin
on E: Exception do
begin
Logger.Log(2, '--Error creating TApiDatabase: ' + E.Message);
raise;
raise EXDataHttpException.Create(500, 'Unable to connect to the database. Please contact support.');
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;
......@@ -69,21 +74,29 @@ function TApiService.TestApi(messageText: string): TJSONObject;
var
requiredVersion: string;
begin
Logger.Log(3, 'IApiService.TestApi called');
try
Logger.Log(3, 'IApiService.TestApi called');
Result := TJSONObject.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
Result := TJSONObject.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
requiredVersion := GetWebClientVersion;
requiredVersion := GetWebClientVersion;
Result.AddPair('messageEcho', messageText);
Result.AddPair('serverTime', DateTimeToStr(Now));
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('messageEcho', messageText);
Result.AddPair('serverTime', DateTimeToStr(Now));
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).');
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;
initialization
RegisterServiceType(TApiService);
......
......@@ -6,7 +6,6 @@ object AppServerModule: TAppServerModule
Top = 16
end
object SparkleStaticServer: TSparkleStaticServer
BaseUrl = 'http://localhost:2006/webPoliceReports/app/'
Dispatcher = SparkleHttpSysDispatcher
Left = 88
Top = 88
......
......@@ -3,38 +3,32 @@ object AuthDatabase: TAuthDatabase
OnDestroy = DataModuleDestroy
Height = 249
Width = 433
object ucHST: TUniConnection
ProviderName = 'MySQL'
Database = 'sleepdb'
Username = 'hstuser'
Server = '192.168.116.135'
object ucDatabase: TUniConnection
ProviderName = 'PostgreSQL'
Port = 5432
LoginPrompt = False
Left = 93
Top = 49
EncryptedPassword = '9AFF92FF8CFF86FF8CFFDEFFCFFFCEFF'
end
object MySQLUniProvider1: TMySQLUniProvider
object PostgreSQLUniProvider1: TPostgreSQLUniProvider
Left = 94
Top = 124
end
object uqUser: TUniQuery
Connection = ucHST
Connection = ucDatabase
SQL.Strings = (
'select * from users')
'select u.* from lems.users u'
'where upper(user_name) = :USER_NAME and u.dept = :AGENCY')
FetchRows = 100
Left = 226
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
......@@ -6,16 +6,14 @@ interface
uses
System.SysUtils, System.Classes, IniFiles, Vcl.Forms, MemDS,
Data.DB, DBAccess, Uni, UniProvider, PostgreSQLUniProvider, MySQLUniProvider;
Data.DB, DBAccess, Uni, UniProvider, PostgreSQLUniProvider;
type
TAuthDatabase = class(TDataModule)
ucHST: TUniConnection;
MySQLUniProvider1: TMySQLUniProvider;
ucDatabase: TUniConnection;
PostgreSQLUniProvider1: TPostgreSQLUniProvider;
uqUser: TUniQuery;
uqUseruser_id: TIntegerField;
uqUseruser_name: TStringField;
uqUseruser_password: TStringField;
uqAgencyConfig: TUniQuery;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
......@@ -44,12 +42,8 @@ procedure TAuthDatabase.DataModuleCreate(Sender: TObject);
begin
Logger.Log(5, 'TAuthDatabase.DataModuleCreate');
try
ucHST.Database := IniEntries.dbDatabase;
ucHST.Server := IniEntries.dbServer;
ucHST.Port := IniEntries.dbPort;
ucHST.Username := IniEntries.dbUsername;
ucHST.Password := IniEntries.dbPassword;
ucHST.Connect;
IniEntries.ConfigureConnection(ucDatabase);
ucDatabase.Connect;
except
on E: Exception do
begin
......@@ -61,7 +55,7 @@ end;
procedure TAuthDatabase.DataModuleDestroy(Sender: TObject);
begin
ucHST.Connected := false;
ucDatabase.Connected := false;
end;
......
......@@ -15,6 +15,9 @@ object AuthServerModule: TAuthServerModule
SwaggerUIOptions.TryItOutEnabled = True
Left = 91
Top = 92
object XDataServerForward: TSparkleForwardMiddleware
OnAcceptProxy = XDataServerForwardAcceptProxy
end
object XDataServerLogging: TSparkleGenericMiddleware
OnMiddlewareCreate = XDataServerLoggingMiddlewareCreate
end
......
......@@ -12,15 +12,17 @@ uses
Sparkle.Comp.Server, Sparkle.Comp.JwtMiddleware, XData.Comp.Server,
Sparkle.Comp.HttpSysDispatcher, Sparkle.Comp.CompressMiddleware,
Sparkle.Comp.CorsMiddleware, Sparkle.HttpServer.Module,
Sparkle.HttpServer.Context, Sparkle.Comp.GenericMiddleware;
Sparkle.HttpServer.Context, Sparkle.Comp.GenericMiddleware, Sparkle.Comp.ForwardMiddleware;
type
TAuthServerModule = class(TDataModule)
SparkleHttpSysDispatcher: TSparkleHttpSysDispatcher;
XDataServer: TXDataServer;
XDataServerForward: TSparkleForwardMiddleware;
XDataServerLogging: TSparkleGenericMiddleware;
XDataServerCORS: TSparkleCorsMiddleware;
XDataServerCompress: TSparkleCompressMiddleware;
procedure XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
procedure XDataServerLoggingMiddlewareCreate(Sender: TObject;
var Middleware: IHttpServerMiddleware);
private
......@@ -76,4 +78,9 @@ begin
Middleware := TLoggingMiddleware.Create(Logger);
end;
procedure TAuthServerModule.XDataServerForwardAcceptProxy(Sender: TObject; const Value: string; var Accept: Boolean);
begin
Accept := True;
end;
end.
......@@ -12,11 +12,25 @@ const
AUTH_MODEL = 'Auth';
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)]
IAuthService = interface(IInvokable)
['{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;
end;
......
......@@ -3,8 +3,10 @@ unit Auth.ServiceImpl;
interface
uses
System.AnsiStrings,
System.SysUtils,
System.Classes,
System.Generics.Collections,
System.JSON,
System.IniFiles,
System.DateUtils,
......@@ -28,9 +30,10 @@ type
strict private
AuthDb: TAuthDatabase;
function GetWebClientVersion: string;
function Decrypt(inStr, keyStr: AnsiString): AnsiString;
public
// Note: CHANGED - Login now takes a plain text password (kgOrders style)
function Login(const username, password, clientVersion: string): string;
function Login(username, password, agency, clientVersion: string): string;
function GetAgencyConfigList: TAgencyConfigList;
function VerifyVersion(clientVersion: string): TJSONObject;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
......@@ -43,14 +46,21 @@ begin
inherited;
try
AuthDb := TAuthDatabase.Create(nil);
Logger.Log(5, 'TAuthService.AfterConstruction - AuthDb created');
except
on E: Exception do
begin
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;
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;
Logger.Log(5, 'TAuthService.AfterConstruction - AuthDb created');
end;
procedure TAuthService.BeforeDestruction;
......@@ -77,90 +87,159 @@ function TAuthService.VerifyVersion(clientVersion: string): TJSONObject;
var
webClientVersion: string;
begin
Logger.Log(5, 'TAuthService.VerifyVersion(clientVersion: ' + clientVersion + ')');
try
Logger.Log(5, 'TAuthService.VerifyVersion(clientVersion: ' + clientVersion + ')');
Result := TJSONObject.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
Result := TJSONObject.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
webClientVersion := GetWebClientVersion;
Result.AddPair('webClientVersion', webClientVersion);
webClientVersion := GetWebClientVersion;
Result.AddPair('webClientVersion', webClientVersion);
if webClientVersion = '' then
begin
Result.AddPair('error', 'webClientVersion is not configured.');
Exit;
end;
if webClientVersion = '' then
begin
Result.AddPair('error', 'webClientVersion is not configured.');
Exit;
end;
if clientVersion <> webClientVersion then
begin
Logger.Log(1, 'webApp version mismatch client ver: ' + clientVersion + ' required ver: ' + webClientVersion);
Result.AddPair('error',
'webApp version mismatch' + sLineBreak +
' Client version: ' + clientVersion + sLineBreak +
' Server version: ' + webClientVersion + sLineBreak +
'Please clear cache and reload.');
if clientVersion <> webClientVersion then
begin
Logger.Log(1, 'webApp version mismatch client ver: ' + clientVersion + ' required ver: ' + webClientVersion);
Result.AddPair('error',
'webApp version mismatch' + sLineBreak +
' Client version: ' + clientVersion + sLineBreak +
' Server version: ' + webClientVersion + sLineBreak +
'Please clear cache and reload.');
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;
function TAuthService.Login(const username, password, clientVersion: string): string;
function TAuthService.Login(username, password, agency, clientVersion: string): string;
var
sql: string;
storedHash: string;
passwordHash: string;
webClientVersion: string;
passwordKey: AnsiString;
decryptedPassword: string;
jwt: TJWT;
begin
Logger.Log(3, Format('AuthService.Login - User: "%s"', [username]));
try
sql := 'select user_id, user_name, user_password from users where user_name = ' + QuotedStr(username) + ' limit 1';
DoQuery(AuthDb.uqUser, sql);
Logger.Log(3, Format('AuthService.Login - User: "%s" Agency: "%s"', [username, agency]));
if (Trim(username) = '') or (Trim(password) = '') or (Trim(agency) = '') then
raise EXDataHttpUnauthorized.Create('Username, password, and agency are required');
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
raise EXDataHttpUnauthorized.Create('Invalid username or password');
if AuthDb.uqUser.FieldByName('active').AsString = 'F' then
raise EXDataHttpUnauthorized.Create('User not active');
passwordKey := 'wx3cFo$kIf2jrk(gOmvi7uvPfk*iorE8@kfm+nvR6jfh=swDqalpokSjf';
decryptedPassword := UpperCase(Trim(string(Decrypt(AnsiString(AuthDb.uqUser.FieldByName('password').AsString), passwordKey))));
if decryptedPassword <> UpperCase(Trim(password)) then
raise EXDataHttpUnauthorized.Create('Invalid username 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_id', AuthDb.uqUser.FieldByName('userid').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>('server_version', GetWebClientVersion);
Result := TJOSE.SHA256CompactToken(serverConfig.jwtTokenSecret, jwt);
finally
jwt.Free;
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 due to database error: ' + E.Message);
raise EXDataHttpException.Create(500, 'Login failed: Unable to connect to the database.');
Logger.Log(1, 'Login failed: ' + E.ClassName + ': ' + E.Message);
raise EXDataHttpException.Create(500, 'Unable to complete login. Please contact support.');
end;
end;
end;
if AuthDb.uqUser.IsEmpty then
begin
Logger.Log(2, 'Login Error: Invalid username or password');
raise EXDataHttpUnauthorized.Create('Invalid username or password');
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('');
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;
k := Integer(inStr[1]);
tempKeyStr := keyStr;
while Length(tempKeyStr) < 256 do
tempKeyStr := tempKeyStr + tempKeyStr;
if storedHash <> passwordHash then
for i := 1 to Length(inStr) - 1 do
begin
Logger.Log(2, 'Login Error: Invalid username or password');
raise EXDataHttpUnauthorized.Create('Invalid username or password');
end;
webClientVersion := GetWebClientVersion;
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<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>('client_version', clientVersion);
jwt.Claims.SetClaimOfType<string>('server_version', webClientVersion);
Result := TJOSE.SHA256CompactToken(serverConfig.jwtTokenSecret, jwt);
finally
jwt.Free;
k := (k + i) mod 256;
outStr := outStr + AnsiChar(Integer(inStr[i+1]) xor Integer(tempKeyStr[k+1]));
end;
Result := System.AnsiStrings.Trim(outStr);
end;
initialization
......
......@@ -90,7 +90,9 @@ begin
Logger.Log(1, '--- Server Config Values ---');
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, '-- webAppFolder: ' + serverConfig.webAppFolder + IfThen(serverConfig.webAppFolder = 'static', ' [default]', ' [from config]'));
Logger.Log(1, '-- reportsFolder: ' + serverConfig.reportsFolder + IfThen(serverConfig.reportsFolder = 'static\reports\', ' [default]', ' [from config]'));
......
......@@ -3,7 +3,7 @@ unit Common.Ini;
interface
uses
System.SysUtils, System.IniFiles, Vcl.Forms;
System.SysUtils, System.IniFiles, Vcl.Forms, Uni;
type
TIniEntries = class
......@@ -21,6 +21,7 @@ type
public
constructor Create;
procedure ConfigureConnection(Connection: TUniConnection);
property consoleLogLevel: Integer read FConsoleLogLevel;
property fileLogLevel: Integer read FFileLogLevel;
......@@ -60,16 +61,26 @@ begin
FFileLogLevel := iniFile.ReadInteger('Settings', 'FileLogLevel', 3);
FLogFileNum := iniFile.ReadInteger('Settings', 'LogFileNum', 0);
FDBServer := iniFile.ReadString('Database', 'Server', '192.168.116.129');
FDBPort := iniFile.ReadInteger('Database', 'Port', 0);
FDBDatabase := iniFile.ReadString('Database', 'Database', 'kg_order_entry');
FDBUsername := iniFile.ReadString('Database', 'Username', 'root');
FDBPassword := iniFile.ReadString('Database', 'Password', 'emsys01');
FDBServer := iniFile.ReadString('Postgres', 'Server', '');
FDBPort := iniFile.ReadInteger('Postgres', 'Port', 5432);
FDBDatabase := iniFile.ReadString('Postgres', 'Database', 'lems_wcso');
FDBUsername := iniFile.ReadString('Postgres', 'Username', 'postgres');
FDBPassword := iniFile.ReadString('Postgres', 'Password', '');
finally
iniFile.Free;
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;
interface
......
......@@ -66,8 +66,16 @@ procedure TFMain.timerStartServerTimer(Sender: TObject);
begin
timerStartServer.Enabled := False;
Caption := Caption + ' ver ' + exeInfoVersion.FileVersion;
LoadIniEntries;
LoadServerConfig;
try
LoadIniEntries;
LoadServerConfig;
except
on E: Exception do
begin
Logger.Log(1, 'Server startup stopped: ' + E.Message);
Exit;
end;
end;
StartServers;
end;
......@@ -87,12 +95,14 @@ begin
Logger.Log(1, '******************************************************');
Logger.Log(1, '');
Logger.Log(1, '--- Database ---');
Logger.Log(1, '--Database->Server: ' + IniEntries.dbServer);
Logger.Log(1, '--Database->Port: ' + IniEntries.dbPort.ToString);
Logger.Log(1, '--Database->Database: ' + IniEntries.dbDatabase);
Logger.Log(1, '--Database->Username: ' + IniEntries.dbUsername);
Logger.Log(1, '--Database->Password: ' + IniEntries.dbPassword);
Logger.Log(1, '--- Postgres ---');
Logger.Log(1, '--Postgres->Server: ' + IniEntries.dbServer);
Logger.Log(1, '--Postgres->Port: ' + IniEntries.dbPort.ToString);
Logger.Log(1, '--Postgres->Database: ' + IniEntries.dbDatabase);
Logger.Log(1, '--Postgres->Username: ' + IniEntries.dbUsername);
// 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, '--- Settings ---');
......
......@@ -3,6 +3,7 @@ program templateXDataServer;
uses
Vcl.Forms,
FastMM4,
System.Classes,
System.SyncObjs,
System.SysUtils,
Vcl.StdCtrls,
......@@ -69,6 +70,9 @@ var
logTime: TDateTime;
formattedMessage: string;
begin
if logLevel > FLogLevel then
Exit;
FCriticalSection.Acquire;
try
logTime := Now;
......@@ -80,11 +84,16 @@ begin
else
formattedMessage := formattedMessage + '[' + IntToStr(logLevel) + '] ' + logMsg;
if logLevel <= FLogLevel then
FLogMemo.Lines.Add(formattedMessage);
finally
FCriticalSection.Release;
end;
TThread.Queue(nil,
procedure
begin
if Assigned(FLogMemo) and not (csDestroying in FLogMemo.ComponentState) then
FLogMemo.Lines.Add(formattedMessage);
end);
end;
{ TFileLogAppender }
......
......@@ -88,6 +88,10 @@
<VerInfo_Locale>1033</VerInfo_Locale>
<DCC_UnitSearchPath>C:\RADTOOLS\FastMM4;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
<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 Condition="'$(Cfg_2)'!=''">
<DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
......@@ -161,10 +165,10 @@
<Source Name="MainSource">templateXDataServer.dpr</Source>
</Source>
<Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcboffice2k290.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)\dcloffice2k290.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)\bcboffice2k370.bpl">Embarcadero C++Builder Office 2000 Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\bcbofficexp370.bpl">Embarcadero C++Builder Office XP Servers Package</Excluded_Packages>
<Excluded_Packages Name="$(BDSBIN)\dcloffice2k370.bpl">Microsoft Office 2000 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>
</Delphi.Personality>
<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