General tidy.

This commit is contained in:
Andy Howard
2024-06-13 14:32:44 +01:00
parent 0c44e9ddd3
commit bf6bb966bc
159 changed files with 1166 additions and 972 deletions
@@ -54,7 +54,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.App
}
catch (Exception exc)
{
SaLogger.Error(GetType().Name + ".CTR " + ExceptionUtil.GetErrorStateMessage(exc));
SaLogger.Error($"{GetType().Name}.CTR {ExceptionUtil.GetErrorStateMessage(exc)}");
throw;
}
}
@@ -101,7 +101,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.App
/// <summary>Initialise environment - from internal (above) or unit tests.</summary>
protected void InitEnvironment(IWebHostEnvironment env)
{
String fn = GetType().Name + ".InitEnvironment";
Development = env.IsDevelopment();
environmentName = env.EnvironmentName;
SaLogger.LogFilenamePrefix = "Sbm-Web-Onl";
@@ -138,16 +137,16 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.App
}
if (DirectoryUtil.DirectoryExists(LoggingRootFolder))
SaLogger.LogFolder = LoggingRootFolder;
LogApplicationStart(fn);
LogApplicationStart($"{SysUtil.Fn}");
// Control database connection.
SacsDatabaseConsole.OdbcConfig odbcConfig = new SacsDatabaseConsole.OdbcConfig();
// Control database connection.
SacsDatabaseConsole.OdbcConfig odbcConfig = new SacsDatabaseConsole.OdbcConfig();
odbcConfig.location = AppConfig.ControlDatabase.Location;
odbcConfig.user = AppConfig.ControlDatabase.User;
odbcConfig.pword = AppConfig.ControlDatabase.Password;
controlDatabase = SacsDatabaseConsole.OpenOdbcDatabase(odbcConfig);
if (controlDatabase.HasErrorState())
SaLogger.Warn(fn + " Control Database initialisation error: " + controlDatabase.ErrorStateMessage);
SaLogger.Warn($"{SysUtil.Fn} Control Database initialisation error: " + controlDatabase.ErrorStateMessage);
// Configure BusMgr database connections.
foreach (SbmAppConfig.DatabaseConfig dbConfig in AppConfig.BusMgrDatabases)
@@ -166,12 +165,12 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.App
sessionContextData.DbIdentifiers.AddRange(dbConfig.Identifiers);
sessionContexts.Add(sessionContextData.SessionContext.Index, sessionContextData);
}
else SaLogger.Warn(fn + " Database: " + coreDatabase.DatabaseName + ". Initialisation error: " + coreDatabase.ErrorStateMessage);
else SaLogger.Warn($"{SysUtil.Fn} Database: " + coreDatabase.DatabaseName + ". Initialisation error: " + coreDatabase.ErrorStateMessage);
}
}
catch (Exception exc)
{
SaLogger.Error(fn + " " + ExceptionUtil.GetLogMessage(exc));
SaLogger.Error($"{SysUtil.Fn} " + ExceptionUtil.GetLogMessage(exc));
}
}
@@ -99,7 +99,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Association/Ajax/GetList")]
public IActionResult Ajax_AssociationList(Model_Association model)
{
String fn = GetType().Name + ".Ajax_AssociationList";
AjaxResponse_AssociationList responseData = new AjaxResponse_AssociationList(model);
String messageTitle = Localiser["association.caption.associations"];
@@ -201,7 +200,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Association/Ajax/GetItem")]
public IActionResult Ajax_GetItem(Model_Association model)
{
String fn = GetType().Name + ".Ajax_GetItem";
String messageTitle = Localiser["association.caption.association"];
AjaxResponse_Association responseData = new AjaxResponse_Association(model);
@@ -219,7 +217,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
SbmAssociation association = AccountMgr.GetAssociationById(associationId);
if (association == null)
{
SaLogger.Warn(fn + " Failed to retrieve association for Id: '" + model.AssociationId + "'");
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve association for Id: '" + model.AssociationId + "'");
return Json(responseData.SetMessage(messageTitle, Localiser["msg.error.item.id.not.found"]));
}
@@ -240,7 +238,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Association/Ajax/StoreItem")]
public IActionResult Ajax_StoreItem(Model_Association model)
{
String fn = GetType().Name + ".Ajax_StoreItem";
String messageTitle = Localiser["association.caption.association"];
AjaxResponse_Association responseData = new AjaxResponse_Association(model);
@@ -259,12 +256,12 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
bool associationExists = StringUtil.ToBool(model.AssociationExists);
if (associationExists && !SysId.IsValid(associationId))
{
SaLogger.Warn(fn + " Id not specified for existing Association.");
SaLogger.Warn($"{SysUtil.Fn} Id not specified for existing Association.");
return Json(responseData.SetGoHome(messageTitle, Localiser["msg.error.system"]));
}
if (!associationExists && SysId.IsValid(associationId))
{
SaLogger.Warn(fn + " Id specified for new Association: '" + model.AssociationId + "'");
SaLogger.Warn($"{SysUtil.Fn} Id specified for new Association: '" + model.AssociationId + "'");
return Json(responseData.SetGoHome(messageTitle, Localiser["msg.error.system"]));
}
@@ -272,7 +269,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
SbmAssociation association = AccountMgr.GetAssociationById(associationId);
if (association == null && SysId.IsValid(associationId))
{
SaLogger.Warn(fn + " Failed to retrieve association for Id: '" + model.AssociationId + "'");
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve association for Id: '" + model.AssociationId + "'");
return Json(responseData.SetMessage(messageTitle, Localiser["msg.error.item.id.not.found"]));
}
@@ -370,7 +367,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
{
if (!AccountMgr.InsertAssociation(association, DbUpdateInfo))
{
SaLogger.Warn(fn + " Failed to insert association: " + AccountMgr.ErrorStateMessage);
SaLogger.Warn($"{SysUtil.Fn} Failed to insert association: " + AccountMgr.ErrorStateMessage);
return Json(responseData.SetMessage(messageTitle, Localiser["msg.error.item.insert.failed"] + "\n\n" + AccountMgr.ErrorStateMessage));
}
responseData.SetNotification(messageTitle, Localiser["msg.item.created"]);
@@ -379,7 +376,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
{
if (!AccountMgr.UpdateAssociation(association, DbUpdateInfo))
{
SaLogger.Warn(fn + " Failed to update association [Id:" + SysId.ToString(association.Id) + "]: " + AccountMgr.ErrorStateMessage);
SaLogger.Warn($"{SysUtil.Fn} Failed to update association [Id:" + SysId.ToString(association.Id) + "]: " + AccountMgr.ErrorStateMessage);
return Json(responseData.SetMessage(messageTitle, Localiser["msg.error.item.update.failed"] + "\n\n" + AccountMgr.ErrorStateMessage));
}
responseData.SetNotification(messageTitle, Localiser["msg.item.updated"]);
@@ -35,8 +35,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[HttpGet]
public IActionResult Index()
{
String fn = GetType().Name + ".Index";
if (!ValidUserSession)
return RedirectToAction("", "");
@@ -23,7 +23,7 @@ using static Sarand.BusinessMgr.Net.Standard.Base.App.Sbm.Config.Database;
namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
{
//=======================================================================
public class SbmController_Portal : SbmController_Base
public class SbmController_Portal : SbmController_Web
{
//-------------------------------------------------------------------
// Data members.
@@ -55,24 +55,22 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
/// </summary>
protected bool SignUserIn(ISbmUserContext userContext, String dbIdentifier, SaSecurityItem securityItemUser, SbmAffiliate affiliateUser, List<SysIdString> supervisedOrganisations, SbmAssociation associationOrganisation, SbmAffiliate affiliateOrganisation, bool keepLoggedIn, ref String errorMessage)
{
String fn = GetType().Name + ".SignUserIn";
// Validate Security Item and Affiliate, just in case - should have been done before arriving here!
if (securityItemUser == null)
{
SaLogger.Error(fn + " Unable to sign account in - null security item.");
SaLogger.Error($"{SysUtil.Fn} Unable to sign account in - null security item.");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
if (affiliateUser == null)
{
SaLogger.Error(fn + " Unable to sign account in - null affiliate.");
SaLogger.Error($"{SysUtil.Fn} Unable to sign account in - null affiliate.");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
if (!affiliateUser.IsStatusCurrent)
{
SaLogger.Error(fn + " Unable to sign account in - affiliate is not active. Email: " + securityItemUser.EmailAddress);
SaLogger.Error($"{SysUtil.Fn} Unable to sign account in - affiliate is not active. Email: {securityItemUser.EmailAddress}");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
@@ -80,19 +78,19 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
// Organisation.
if (associationOrganisation == null)
{
SaLogger.Error(fn + " Unable to sign account in - null organisation association.");
SaLogger.Error($"{SysUtil.Fn} Unable to sign account in - null organisation association.");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
if (associationOrganisation.AssociationType != Sbm.AssociationType.Internal)
{
SaLogger.Error(fn + " Unable to sign account in - organisation association is not type 'Internal'.");
SaLogger.Error($"{SysUtil.Fn} Unable to sign account in - organisation association is not type 'Internal'.");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
if (affiliateOrganisation == null)
{
SaLogger.Error(fn + " Unable to sign account in - null organisation affiliate.");
SaLogger.Error($"{SysUtil.Fn} Unable to sign account in - null organisation affiliate.");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
@@ -109,7 +107,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
securityItemUser.LastInvalidLoginAt = DateTime.MinValue;
if (!securityConsoleForUser.UpdateSecurityItem(securityItemUser, DbUpdateInfo))
{
SaLogger.Warn(fn + " Failed to update security item for " + securityItemUser.EmailAddress + ": " + securityConsoleForUser.ErrorStateMessage);
SaLogger.Warn($"{SysUtil.Fn} Failed to update security item for {securityItemUser.EmailAddress}: {securityConsoleForUser.ErrorStateMessage}");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
@@ -118,11 +116,11 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
affiliateUser.KeepLoggedIn_Portal = keepLoggedIn;
if (!accountMgrForUser.UpdateAffiliate(affiliateUser, DbUpdateInfo))
{
SaLogger.Warn(fn + " Failed to update affiliate for " + securityItemUser.EmailAddress + ": " + accountMgrForUser.ErrorStateMessage);
SaLogger.Warn($"{SysUtil.Fn} Failed to update affiliate for {securityItemUser.EmailAddress}: {accountMgrForUser.ErrorStateMessage}");
errorMessage = Localiser["security.msg.signin.invalid"];
return false;
}
SaLogger.Info(fn + " User session opened for " + securityItemUser.EmailAddress, true);
SaLogger.Info($"{SysUtil.Fn} User session opened for {securityItemUser.EmailAddress}", true);
}
// Create session.
@@ -139,7 +137,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
/// <summary>Populate the user's profile contact details to the session.</summary>
protected bool RefreshSessionProfileContact(SaSecurityItem securityItemUser, SbmAffiliate affiliateUser, List<SysIdString> supervisedOrganisations, SbmAssociation associationOrganisation, SbmAffiliate affiliateOrganisation)
{
String fn = GetType().Name + ".RefreshSessionProfileContact";
SbmSessionData_Portal sessionData = SessionData_Portal;
SysId affiliateIdUser = sessionData?.User.AffiliateId ?? null;
if (!SysId.IsValid(affiliateIdUser)) return false;
@@ -180,7 +177,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
String keepLoggedInCookieValue = GenerateKeepLoggedInCookieValue();
int cookieExpiresDays = Math.Max(Sbm.Config.Security.SignIn.KeepLoggedIn.CookieExpiresDays_Min, Math.Min(Sbm.Config.Security.SignIn.KeepLoggedIn.CookieExpiresDays_Max, AppConfig.Security.SignIn.KeepLoggedIn.CookieExpiresDays));
SetResponseCookie(CookieName_KeepLoggedIn, keepLoggedInCookieValue, DateTime.Now.AddDays(cookieExpiresDays), true);
SaLogger.Info(this.GetType().Name + ".SetKeepLoggedInCookie 'Keep Logged In' cookie set. Value: " + keepLoggedInCookieValue);
SaLogger.Info($"{SysUtil.Fn} 'Keep Logged In' cookie set. Value: {keepLoggedInCookieValue}");
}
/// <summary>Set the 'Keep Logged In' response cookie to expired with no data.</summary>
@@ -189,7 +186,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
if (StringUtil.IsEmpty(GetRequestCookie(CookieName_KeepLoggedIn))) return;
// Clear cookie by setting expiry date in the past.
SetResponseCookie(CookieName_KeepLoggedIn, "", DateTime.Today.AddDays(-7), true);
SaLogger.Info(GetType().Name + ".ClearKeepLoggedInCookie 'Keep Logged In' cookie cleared.");
SaLogger.Info($"{SysUtil.Fn} 'Keep Logged In' cookie cleared.");
}
//-------------------------------------------------------------------
@@ -269,7 +266,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
keepLoggedInParams.AffiliateIdUser = linkParams.Get(ParamName_KeepLoggedIn_AffiliateIdUser).ToSysId();
keepLoggedInParams.AssociationIdOrganisation = linkParams.Get(ParamName_KeepLoggedIn_AssociationIdOrganisation).ToSysId();
}
if (DebugMode) SaLogger.Info(GetType().Name + ".ExtractKeepLoggedInParams UserAccountId: " + SysId.ToString(keepLoggedInParams.AffiliateIdUser));
if (DebugMode) SaLogger.Info($"{SysUtil.Fn} UserAccountId: {SysId.ToString(keepLoggedInParams.AffiliateIdUser)}");
return keepLoggedInParams;
}
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using Sarand.BusinessMgr.Net.Core.Web.App;
using Sarand.BusinessMgr.Net.Core.Web.Helpers;
using Sarand.BusinessMgr.Net.Core.Web.Portal.Models;
@@ -43,7 +44,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Security/Ajax/Signin")]
public IActionResult Ajax_Signin(Model_Security model)
{
String fn = GetType().Name + ".Ajax_Signin";
AjaxResponse_Signin responseData = new AjaxResponse_Signin(model);
String messageTitle = Localiser["label.signin"];
@@ -76,45 +76,51 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
// User's security item.
SaSecurityItem securityItemUser = GetSecurityItemForSignin(securityConsoleForUser, model);
disposableItems.Add(securityItemUser);
if (securityItemUser == null)
{
SaLogger.Warn(fn + " Failed to retrieve Security Item. Database: " + busMgrDatabase.DatabaseName + ". Email: " + model.EmailAddress);
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve Security Item. Database: {busMgrDatabase.DatabaseName}. Email: {model.EmailAddress}.");
continue;
}
if (!securityItemUser.PasswordMatches(model.Password))
{
SaLogger.Warn($"{SysUtil.Fn} Supplied password doesn't match Security Item. Database: {busMgrDatabase.DatabaseName}. Email: {model.EmailAddress}.");
continue;
}
disposableItems.Add(securityItemUser);
// User's affiliate.
SbmAffiliate affiliateUser = GetAffiliateForSignin(accountMgrForUser, model, securityItemUser);
disposableItems.Add(affiliateUser);
if (affiliateUser == null)
{
SaLogger.Warn(fn + " Failed to retrieve Affiliate for signin. Database: " + busMgrDatabase.DatabaseName + ". UserId: " + SysId.ToString(securityItemUser.Id));
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve Affiliate for signin. Database: {busMgrDatabase.DatabaseName}. UserId: {SysId.ToString(securityItemUser.Id)}.");
continue;
}
disposableItems.Add(affiliateUser);
// User's supervised organisations.
List<SysIdString> supervisedOrganisations = accountMgrForUser.GetAffiliatesSupervisedBy(affiliateUser.Id);
if (supervisedOrganisations.IsEmpty())
{
SaLogger.Warn(fn + " User has no supervised organisations. Database: " + busMgrDatabase.DatabaseName + ". Email: " + model.EmailAddress);
SaLogger.Warn($"{SysUtil.Fn} User has no supervised organisations. Database: {busMgrDatabase.DatabaseName}. Email: {model.EmailAddress}.");
continue;
}
userContext.RefreshUser(securityItemUser, affiliateUser, supervisedOrganisations);
// User's organisation association.
SbmAssociation associationOrganisation = GetOrganisationAssociationForSignIn(accountMgrForUser, model, affiliateUser, supervisedOrganisations);
SbmAssociation associationOrganisation = GetOrganisationAssociationForSignIn(accountMgrForUser, model, userContext);
disposableItems.Add(associationOrganisation);
if (associationOrganisation == null)
{
SaLogger.Warn(fn + " Failed to identify Organisation Association. Database: " + busMgrDatabase.DatabaseName + ". Email: " + model.EmailAddress);
SaLogger.Warn($"{SysUtil.Fn} Failed to identify Organisation Association. Database: {busMgrDatabase.DatabaseName}. Email: {model.EmailAddress}.");
continue;
}
disposableItems.Add(associationOrganisation);
// User's organisation affiliate.
SbmAffiliate affiliateOrganisation = accountMgrForUser.GetAffiliateById(associationOrganisation?.Id ?? null);
SbmAffiliate affiliateOrganisation = accountMgrForUser.GetAffiliateById(associationOrganisation?.AffiliateIdOwner ?? null);
disposableItems.Add(affiliateOrganisation);
if (affiliateOrganisation == null)
{
SaLogger.Warn(fn + " Failed to retrieve Affiliate for organisation. Database: " + busMgrDatabase.DatabaseName + ". Id: " + SysId.ToString(associationOrganisation?.Id ?? null));
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve Affiliate for organisation. Database: {busMgrDatabase.DatabaseName}. Id: " + SysId.ToString(associationOrganisation?.Id ?? null));
continue;
}
@@ -127,7 +133,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
}
if (!(SessionData_Portal?.ValidUserSession ?? false))
{
SaLogger.Warn(fn + " Failed to identify Suitable database. Email: " + model.EmailAddress);
SaLogger.Warn($"{SysUtil.Fn} Failed to identify Suitable database. Email: {model.EmailAddress}.");
return Json(responseData.SetControlError(nameof(model.EmailAddress), model.Localiser["security.msg.signin.invalid"]));
}
@@ -140,13 +146,11 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
//-------------------------------------------------------------------
private SaSecurityItem GetSecurityItemForSignin(SaSecurityConsole securityConsoleForUser, Model_Security model)
{
String fn = GetType().Name + ".GetSecurityItemForSignin";
// Retrieve security item by email address.
SaSecurityItem securityItemUser = securityConsoleForUser.GetUserByEmail(model.EmailAddress);
if (securityItemUser == null)
{
SaLogger.Warn(fn + " Failed to retrieve Security Item for email: " + model.EmailAddress, true);
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve Security Item for email: {model.EmailAddress}.", true);
return null;
}
@@ -157,8 +161,8 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
securityItemUser.InvalidLoginCount++;
securityItemUser.LastInvalidLoginAt = DateTime.Now;
if (!securityConsoleForUser.UpdateSecurityItem(securityItemUser, DbUpdateInfo))
SaLogger.Warn(fn + " Failed to store invalid sign-in attempt against User: " + model.EmailAddress + ". " + AccountMgr.ErrorStateMessage, true);
SaLogger.Warn(fn + " Attempt to sign-in to User " + model.EmailAddress + " with invalid password. Attempt: " + securityItemUser.InvalidLoginCount, true);
SaLogger.Warn($"{SysUtil.Fn} Failed to store invalid sign-in attempt against User: {model.EmailAddress}. {AccountMgr.ErrorStateMessage}", true);
SaLogger.Warn($"{SysUtil.Fn} Attempt to sign-in to User {model.EmailAddress} with invalid password. Attempt: {securityItemUser.InvalidLoginCount}.", true);
securityItemUser.Dispose(); securityItemUser = null;
return null;
}
@@ -169,8 +173,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
//-------------------------------------------------------------------
private SbmAffiliate GetAffiliateForSignin(SbmAccountMgr accountMgrForUser, Model_Security model, SaSecurityItem securityItemUser)
{
String fn = GetType().Name + ".GetAffiliateForSignin";
// Identify the contact asociated with the security item.
SbmAffiliate.Params prmAffiliate = new SbmAffiliate.Params();
prmAffiliate.UserId = securityItemUser.Id;
@@ -179,14 +181,14 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
if (affiliate == null)
{
SaLogger.Warn(fn + " Failed to retrieve Affiliate for User Id: " + SysId.ToString(securityItemUser.Id) + ". Email: " + model.EmailAddress, true);
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve Affiliate for User Id: {SysId.ToString(securityItemUser.Id)}. Email: {model.EmailAddress}.", true);
return null;
}
// Validate status.
if (affiliate.Status != SaStatus.Current)
{
SaLogger.Warn(fn + " Invalid Affiliate status for User Id: " + SysId.ToString(securityItemUser.Id) + ". Email: " + model.EmailAddress + ". Found: " + affiliate.Status.ToString() + ". Expected: Current.", true);
SaLogger.Warn($"{SysUtil.Fn} Invalid Affiliate status for User Id: {SysId.ToString(securityItemUser.Id)}. Email: {model.EmailAddress}. Found: {affiliate.Status.ToString()}. Expected: Current.", true);
affiliate.Dispose(); affiliate = null;
return null;
}
@@ -195,21 +197,46 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
}
//-------------------------------------------------------------------
private SbmAssociation GetOrganisationAssociationForSignIn(SbmAccountMgr accountMgrForUser, Model_Security model, SbmAffiliate affiliateUser, List<SysIdString> supervisedOrganisations)
/// <summary>
/// Identify the organisation for the user to login to - either last selected (via SysParam) or first in list.
/// </summary>
private SbmAssociation GetOrganisationAssociationForSignIn(SbmAccountMgr accountMgrForUser, Model_Security model, SbmUserContext userContext)
{
String fn = GetType().Name + ".GetOrganisationAssociationForSignIn";
foreach (SysIdString supervisedOrganisation in supervisedOrganisations)
// Previously selected organisation is stored in user params (SysParam table).
SbmSysParamCache sysParamCache = new SbmSysParamCache(userContext);
SysId affiliateIdOrganisation = StringUtil.ToSysId(sysParamCache.GetUserParamValue(SbmSysParamCache.ParamName_SelectedCompany));
SbmAssociation associationOrganisation = null;
foreach (SysIdString supervisedOrganisation in userContext.User.SupervisedOrganisations)
{
SbmAssociation associationOrganisation = accountMgrForUser.GetAssociationByOwnerTypeTarget(supervisedOrganisation.Id, Sbm.AssociationType.Internal, supervisedOrganisation.Id);
if (associationOrganisation == null)
SbmAssociation associationOrganisationCandidate = accountMgrForUser.GetAssociationByOwnerTypeTarget(supervisedOrganisation.Id, Sbm.AssociationType.Internal, supervisedOrganisation.Id);
if (associationOrganisationCandidate == null)
{
SaLogger.Warn(fn + " Failed to retrieve internal association for affiliate Id: " + SysId.ToString(supervisedOrganisation.Id));
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve internal association for affiliate Id: {SysId.ToString(supervisedOrganisation.Id)}.");
continue;
}
return associationOrganisation;
if (associationOrganisationCandidate.AffiliateIdOwner.Equals(affiliateIdOrganisation))
{
// Previously selected organisation.
associationOrganisation = associationOrganisationCandidate;
break;
}
if (associationOrganisation == null)
// Make a note of the first organisation in case none selected.
associationOrganisation = associationOrganisationCandidate;
}
SaLogger.Warn(fn + " Failed to retrieve any internal associations for supervised organisations. Email: " + model.EmailAddress);
return null;
if (associationOrganisation != null)
{
// Make a note of the selection.
sysParamCache.SetUserParamValue(SbmSysParamCache.ParamName_SelectedCompany, SysId.ToString(associationOrganisation.AffiliateIdOwner));
}
else
SaLogger.Warn($"{SysUtil.Fn} Failed to retrieve any internal associations for supervised organisations. Email: {model.EmailAddress}.");
if (sysParamCache.Modified)
{
sysParamCache.Store();
SaLogger.Info($"{SysUtil.Fn} User params stored.");
}
return associationOrganisation;
}
//-------------------------------------------------------------------
@@ -223,7 +250,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Security/Ajax/KeepLoggedIn")]
public ActionResult Ajax_KeepLoggedIn(Model_Security model)
{
String fn = GetType().Name + ".Ajax_KeepLoggedIn";
AjaxResponse_KeepLoggedIn responseData = new AjaxResponse_KeepLoggedIn();
// Validate session and referrer.
@@ -258,7 +284,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Security/Ajax/SignOut")]
public ActionResult Ajax_SignOut(Model_Security model)
{
String fn = GetType().Name + ".Ajax_SignOut";
AjaxResponse_SignOut responseData = new AjaxResponse_SignOut(model);
String messageTitle = Localiser["label.signout"];
@@ -272,14 +297,14 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
SbmAffiliate affiliateUser = AccountMgr.GetAffiliateById(SessionData_Portal.User.AffiliateId);
if (affiliateUser == null)
{
SaLogger.Warn(fn + " System error - failed to retrieve account details.");
SaLogger.Warn($"{SysUtil.Fn} System error - failed to retrieve account details.");
return Json(responseData.SetMessage(messageTitle, Localiser["msg.error.system"]));
}
// Clear user session.
String emailAddress = SessionData.User.EmailAddress;
CloseUserSession();
SaLogger.Info(fn + " User session closed for " + emailAddress, true);
SaLogger.Info($"{SysUtil.Fn} User session closed for {emailAddress}.", true);
// Clear 'Keep Logged In' cookie.
ClearKeepLoggedInCookie();
@@ -329,7 +354,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Security/Ajax/StorePassword")]
public ActionResult Ajax_StorePassword(Model_Security model)
{
String fn = GetType().Name + ".Ajax_StorePassword";
AjaxResponse_ChangePassword responseData = new AjaxResponse_ChangePassword(model);
String messageTitle = Localiser["security.caption.change.password"];
@@ -372,7 +396,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
}
else
{
SaLogger.Warn(fn + " 'Request Password' parameters supplied but invalid. Email: " + requestPasswordParams.EmailAddress + ". SecurityItemId: " + SysId.ToString(requestPasswordParams.SecurityItemId) + ". AffiliateId: " + SysId.ToString(requestPasswordParams.AffiliateId));
SaLogger.Warn($"{SysUtil.Fn} 'Request Password' parameters supplied but invalid. Email: {requestPasswordParams.EmailAddress}. SecurityItemId: {SysId.ToString(requestPasswordParams.SecurityItemId)}. AffiliateId: {SysId.ToString(requestPasswordParams.AffiliateId)}.");
if (securityItemUser != null) securityItemUser.Dispose(); securityItemUser = null;
if (affiliateUser != null) affiliateUser.Dispose(); affiliateUser = null;
sessionContextForUser = null;
@@ -432,10 +456,10 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
securityItemUser.PasswordHistory.RemoveAt(securityItemUser.PasswordHistory.Count - 1);
if (!securityConsole.UpdateSecurityItem(securityItemUser, DbUpdateInfo))
{
SaLogger.Warn(fn + " Failed to change password for " + securityItemUser.EmailAddress + ": " + securityConsole.ErrorStateMessage);
SaLogger.Warn($"{SysUtil.Fn} Failed to change password for {securityItemUser.EmailAddress}: {securityConsole.ErrorStateMessage}");
return Json(responseData.SetControlError(nameof(model.Password), Localiser["security.msg.change.password.failed"]));
}
SaLogger.Info(fn + " Password changed for " + securityItemUser.EmailAddress, true);
SaLogger.Info($"{SysUtil.Fn} Password changed for {securityItemUser.EmailAddress}.", true);
}
// Cleanup. NB The Security Item and/or Affiliate aren't disposed when the method
@@ -468,7 +492,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[Route("Security/Ajax/RequestPassword")]
public ActionResult Ajax_RequestPassword(Model_Security model)
{
String fn = GetType().Name + ".Ajax_RequestPassword";
AjaxResponse_RequestPassword responseData = new AjaxResponse_RequestPassword(model);
String messageTitle = Localiser["security.caption.request.password"];
@@ -510,16 +533,16 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
emailData.Subject = Localiser["security.caption.request.password"];
PopulateRequestPasswordEmailBody(emailConsole, userContext, emailData, securityItemUser, affiliateUser);
if (emailConsole.SendEmail(emailData))
SaLogger.Info(fn + " Password request email sent to " + model.EmailAddress, true);
else SaLogger.Warn(fn + " Failed to send password request email to " + model.EmailAddress);
SaLogger.Info($"{SysUtil.Fn} Password request email sent to {model.EmailAddress}.", true);
else SaLogger.Warn($"{SysUtil.Fn} Failed to send password request email to {model.EmailAddress}.");
}
else SaLogger.Warn(fn + " Unable to send password request email to " + model.EmailAddress + " - affiliate is not active");
else SaLogger.Warn($"{SysUtil.Fn} Unable to send password request email to {model.EmailAddress} - affiliate is not active");
}
else SaLogger.Warn(fn + " Unable to send password request email to " + model.EmailAddress + " - affiliate does not exist. UserId: " + SysId.ToString(securityItemUser.Id));
else SaLogger.Warn($"{SysUtil.Fn} Unable to send password request email to {model.EmailAddress} - affiliate does not exist. UserId: {SysId.ToString(securityItemUser.Id)}.");
}
}
}
else SaLogger.Warn(fn + " Unable to send password request email to " + model.EmailAddress + " - security item does not exist.");
else SaLogger.Warn($"{SysUtil.Fn} Unable to send password request email to {model.EmailAddress} - security item does not exist.");
}
}
}
@@ -591,17 +614,17 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
{
List<String> values = new List<String>();
if (!StringUtil.IsBlank(DbIdentifier))
values.Add("DbIdentifier: " + DbIdentifier);
values.Add($"DbIdentifier: {DbIdentifier}");
if (!StringUtil.IsBlank(EmailAddress))
values.Add("Email: " + EmailAddress);
values.Add($"Email: {EmailAddress}");
if (SysId.IsValid(SecurityItemId))
values.Add("SecurityItemId: " + SysId.ToString(SecurityItemId));
values.Add($"SecurityItemId: {SysId.ToString(SecurityItemId)}");
if (SysId.IsValid(AffiliateId))
values.Add("AffiliateId: " + SysId.ToString(AffiliateId));
values.Add($"AffiliateId: {SysId.ToString(AffiliateId)}");
if (DateUtil.IsValid(ExpiresAt))
values.Add("Expires: " + DateUtil.FormatXmlDateTime(ExpiresAt));
values.Add($"Expires: {DateUtil.FormatXmlDateTime(ExpiresAt)}");
if (!StringUtil.IsBlank(Token))
values.Add("Token: " + Token);
values.Add($"Token: {Token}");
return values;
}
/// <summary>Verifiy that the email and account Ids are populated and the data hasn't expired.</summary>
@@ -63,7 +63,6 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
[HttpGet, HttpPost]
public IActionResult ChangePassword(Model_Security model)
{
String fn = GetType().Name + ".ChangePassword";
bool validSessionRequired = true;
if (Request.Method.EqualsCI(HttpMethods.Get))
@@ -74,7 +73,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Controllers
RequestPasswordParams requestPasswordParams = ExtractRequestPasswordLinkParams(encryptedParams);
if (requestPasswordParams.IsValid())
{
String logPrefix = fn + " 'Request Password' parameters supplied but ";
String logPrefix = $"{SysUtil.Fn} 'Request Password' parameters supplied but ";
String logSuffix = requestPasswordParams.GetValidParams().Concat("", " ", ".");
// User may be defined on any one of the BusinessMgr databases - need to find out which.
// Identify session contexts with a BusMgr database that hosts the specified email address.
@@ -102,7 +102,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Models
// Validation.
//-------------------------------------------------------------------
// Association validation.
public bool ValidateAssociationData(SbmController_Base.AjaxResponse_Data responseData)
public bool ValidateAssociationData(SbmController_Web.AjaxResponse_Data responseData)
{
//---------------------------------------------------------------
@@ -58,7 +58,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Models
// Validation.
//-------------------------------------------------------------------
// Commodity validation.
public bool ValidateCommodityData(SbmController_Base.AjaxResponse_Data responseData)
public bool ValidateCommodityData(SbmController_Web.AjaxResponse_Data responseData)
{
// Commodity Type.
if (CommodityType != null)
@@ -66,7 +66,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Models
// Validation.
//-------------------------------------------------------------------
// Affiliate validation.
public bool ValidateAffiliateData(SbmController_Base.AjaxResponse_Data responseData)
public bool ValidateAffiliateData(SbmController_Web.AjaxResponse_Data responseData)
{
// Affiliate Type.
if (ContactType != null)
@@ -44,7 +44,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Models
// Validation.
//-------------------------------------------------------------------
// Sign-in.
public bool ValidateSignInData(SbmController_Base.AjaxResponse_Data responseData)
public bool ValidateSignInData(SbmController_Web.AjaxResponse_Data responseData)
{
{
// Database context.
@@ -77,7 +77,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Models
//-------------------------------------------------------------------
// Change password.
public bool ValidateChangePasswordData(SaSecurityItem securityItemUser, SbmAffiliate affiliateUser, SbmController_Base.AjaxResponse_Data responseData)
public bool ValidateChangePasswordData(SaSecurityItem securityItemUser, SbmAffiliate affiliateUser, SbmController_Web.AjaxResponse_Data responseData)
{
// Validate Passwords.
// NB Do not return the password values in the response.
@@ -110,7 +110,7 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Models
//-------------------------------------------------------------------
// Request Password.
public bool ValidateRequestPasswordData(SbmController_Base.AjaxResponse_Data responseData)
public bool ValidateRequestPasswordData(SbmController_Web.AjaxResponse_Data responseData)
{
{
// Database context.
@@ -17,6 +17,10 @@ namespace Sarand.BusinessMgr.Net.Core.Web.Portal.Models
{
}
//-------------------------------------------------------------------
// Properties.
public String OrganisationName { get { return SessionData?.Organisation?.DisplayName ?? ""; } }
//-------------------------------------------------------------------
}
//=======================================================================
@@ -16,7 +16,7 @@
@using (@Html.BeginForm(FormMethod.Post, new { @id = "frmSignIn", @class = "sbm-form" }))
{
<div class="spacer4"></div>
<div class="spacer2"></div>
<div class="sbm-form-control DbIdentifier">
<div class="sbm-label">
<label for="ifEmailAddress"><span>@Localiser["label.context"]</span><span class="required">&nbsp;*</span></label>
@@ -27,7 +27,7 @@
<div class="sbm-message"></div>
</div>
<div class="spacer2"></div>
<div class="spacer"></div>
<div class="sbm-form-control EmailAddress">
<div class="sbm-label">
<label for="ifEmailAddress"><span>@Localiser["label.email"]</span><span class="required">&nbsp;*</span></label>
@@ -38,7 +38,7 @@
<div class="sbm-message"></div>
</div>
<div class="spacer2"></div>
<div class="spacer"></div>
<div class="sbm-form-control Password">
<div class="row">
<div class="col-6">
@@ -53,7 +53,7 @@
<div class="sbm-message"></div>
</div>
<div class="spacer2"></div>
<div class="spacer"></div>
<div class="sbm-form-control">
<div class="row">
<div class="col-6">
@@ -67,7 +67,7 @@
</div>
</div>
<div class="spacer4"></div>
<div class="spacer2"></div>
<div class="">
<div id="pbSignIn" class="sbm-button-action fullwidth pointer" style="margin:16px 0;">@Localiser["label.signin"]</div>
</div>
@@ -60,7 +60,7 @@
sbm.url.home = '@Model.RedirectLocation.Home';
sbm.url.sessionExpired = '@Model.RedirectLocation.Home_SessionExpired';
sbm.form.calendarDateFormat = '@(Model.CalendarDateFormat)';
sbm.lbl.calendar='@Localiser.GetJavascriptText("label.calendar")';
sbm.lbl.calendar = '@Localiser.GetJavascriptText("label.calendar")';
sbm.dlg.title.alert = '@Localiser.GetJavascriptText("dialog.title.alert")';
sbm.dlg.title.confirm = '@Localiser.GetJavascriptText("dialog.title.confirm")';
sbm.dlg.title.progress = '@Localiser.GetJavascriptText("dialog.title.progress")';
@@ -80,7 +80,7 @@
sbm.msg.dataRefreshing = '@Localiser.GetJavascriptText("msg.data.refreshing")';
sbm.msg.dataQuerying = '@Localiser.GetJavascriptText("msg.data.querying")';
sbm.msg.dataNoneFound = '@Localiser.GetJavascriptText("msg.data.noneFound")';
sbm.maxProfileImageSize = 2*10**6;
sbm.maxProfileImageSize = 2 * 10 ** 6;
sbm.sessionCookieName = '@Model.SessionCookieName';
sbm.awaitingLogin = @awaitingLogin;
sbm.keepLoggedIn = @keepLoggedIn;
@@ -152,7 +152,10 @@
@* Footer *@
<footer id="sbm-page-footer" class="">
<div class="container">
@(Model.CopyrightNotice) - Sarand BusinessMgr Portal
<div class="row">
<div class="col-md-6 text-center text-md-left">@(Model.OrganisationName)</div>
<div class="col-md-6 text-center text-md-right">@(Model.CopyrightNotice) - Sarand BusinessMgr Portal</div>
</div>
</div>
</footer>