using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Sarand.Core.App; using Sarand.Core.Base; using Sarand.Core.Bus; using Sarand.Core.CodeTypes; using Sarand.Core.Security; using Sarand.OperationsMgr.Core.App; using Sarand.OperationsMgr.Web.App; using Sarand.OperationsMgr.Web.Models; using Sarand.OperationsMgr.Web.System; using Sarand.Win.Dbas.Base; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Sarand.OperationsMgr.Web.Controllers { //======================================================================= public class Controller_Base : Controller { //------------------------------------------------------------------- // Data members. private List assetTypes; //------------------------------------------------------------------- // Protected construction - use derived classes. protected Controller_Base (OpnLocaliser localiser) : base() { Localiser = localiser; // Initialise console (debug) logging listener. if (Directory.Exists(App.LoggingRootFolder)) OpnConsoleListener.ConfigureDebugListener(App.LoggingRootFolder); if (SacsSystem.DebugMode) Logger.Trace(GetType().Name + ".CTR"); } //------------------------------------------------------------------- // Properties. protected SaOperationsMgrWebApp App { get { return SaOperationsMgrWebApp.GetInstance(); } } public OpnLocaliser Localiser { get; } //------------------------------------------------------------------- // C u l t u r e //------------------------------------------------------------------- private string LanguageIso2 { get { var feature = HttpContext.Features.Get(); return feature.RequestCulture.UICulture.TwoLetterISOLanguageName.ToLower(); } } //------------------------------------------------------------------- // R e d i r e c t i o n L o c a t i o n s //------------------------------------------------------------------- protected enum RedirectLocation { Home, Home_SessionExpired, } protected String GetRedirectLocation (RedirectLocation redirectLocation) { switch (redirectLocation) { case RedirectLocation.Home: return "/Home"; case RedirectLocation.Home_SessionExpired: return "/Home?SessionExpired"; } return ""; } //------------------------------------------------------------------- // A c t i o n E v e n t s //------------------------------------------------------------------- public override void OnActionExecuting (ActionExecutingContext context) { //if (SacsSystem.DebugMode) Logger.Trace(GetType().Name + ".OnActionExecuting"); base.OnActionExecuting(context); } public override void OnActionExecuted (ActionExecutedContext context) { //if (SacsSystem.DebugMode) Logger.Trace(GetType().Name + ".OnActionExecuted"); ViewData["CopyrightNotice"] = new HtmlString(OpnSystem.GetCopyrightNotice(true)); // Refreh model properties. Model_Base baseModel = ViewData.Model as Model_Base; if (baseModel != null) { // Session data. baseModel.SessionData = SessionData; baseModel.AwaitingLogin = !ValidSession; // Redirect locations. baseModel.RedirectLocation.Home = GetRedirectLocation(RedirectLocation.Home); baseModel.RedirectLocation.Home_SessionExpired = GetRedirectLocation(RedirectLocation.Home_SessionExpired); } // Store session data if present - as potentially modfied. if (sessionData != null) { String sessionDataJson = JsonConvert.SerializeObject(sessionData); HttpContext.Session.Set(SessionKey_SessionConfig, sessionDataEncoding.GetBytes(sessionDataJson)); if (baseModel != null) baseModel.SessionIdx = SessionData.SessionContext.Index; } base.OnActionExecuted(context); } //------------------------------------------------------------------- // M o d e l //------------------------------------------------------------------- protected void InitModel (Model_Base model) { model.AwaitingLogin = !ValidSession; } //------------------------------------------------------------------- // S e s s i o n //------------------------------------------------------------------- private SessionData sessionData; public static readonly String SessionKey_SessionConfig = "OpnUserSessionConfig"; private static readonly Encoding sessionDataEncoding = Encoding.UTF8; private class OpnSessionDataContractResolver : DefaultContractResolver { // To allow private properties to be deserialised. protected override List GetSerializableMembers (Type objectType) { var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; MemberInfo[] fields = objectType.GetFields(flags); return fields .Concat(objectType.GetProperties(flags).Where(propInfo => propInfo.CanWrite)) .ToList(); } protected override IList CreateProperties (Type type, MemberSerialization memberSerialization) { return base.CreateProperties(type, MemberSerialization.Fields); } }; JsonSerializerSettings OpnSessionDataJsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new OpnSessionDataContractResolver() }; public bool ValidSession { get { return (SessionData != null && SysId.IsValid(SessionData.User.Id)); } } public SessionData SessionData { get { try { // Retrieve session data if not already in controller. if (sessionData == null) { byte[] sessionDataBytes = null; HttpContext.Session.TryGetValue(SessionKey_SessionConfig, out sessionDataBytes); if (sessionDataBytes != null) { String sessionDataJson = sessionDataEncoding.GetString(sessionDataBytes); sessionData = JsonConvert.DeserializeObject(sessionDataJson, OpnSessionDataJsonSerializerSettings); } } return sessionData; } catch (Exception exc) { Logger.Warn(GetType().Name + ".SessionData " + exc.GetType().Name + " - " + exc.Message + exc.GetStackEntries().Concat("", "\n\t")); } return null; } } protected bool OpenUserSession (OpnSessionContext sessioContext, SysId userId, String userCode, String userName) { // Validate user properties. if (!SysId.IsValid(userId)) return false; if (StringUtil.IsEmpty(userCode)) return false; if (StringUtil.IsEmpty(userName)) return false; // Close previous session. CloseUserSession(); // Open session. sessionData = new SessionData(sessioContext, userId, userCode, userName); return true; } protected void CloseUserSession () { HttpContext.Session.Clear(); sessionData = null; } //------------------------------------------------------------------- // A j a x A c t i o n s //------------------------------------------------------------------- protected static readonly Encoding ajaxResponseEncoding = Encoding.UTF8; public class AjaxResponse { // Response status. public bool Success { get; set; } = false; public bool SessionExpired { get; private set; } = false; public bool GoHome { get; private set; } = false; public AjaxResponse SetSessionExpired (String title, String text) { SessionExpired = true; return SetMessage(title, text); } public AjaxResponse SetGoHome (String title, String text) { GoHome = true; return SetMessage(title, text); } // Message - displays alert popup. public class MessageData { public String Title { get; set; } public String Text { get; set; } } public MessageData Message { get; private set; } public AjaxResponse SetMessage (String title, String text) { Message = new MessageData() { Title = title, Text = text }; return this; } // Notification - briefly displays after response received. public class NotificationData { public String Title { get; set; } public String Message { get; set; } } public NotificationData Notification { get; private set; } public bool HasNotification { get { return Notification != null; } } public AjaxResponse SetNotification (String title, String message) { Notification = new NotificationData() { Title = title, Message = message }; return this; } // Paged data. public class PagingData { public bool Paged { get { return (PageNo > 0 && PageLength > 0 && ItemTotal > PageLength); } } public uint PageNo { get; set; } = 0; public ushort PageLength { get; set; } = 0; public uint PageCount { get { return (PageLength > 0 ? (uint)Math.Ceiling((decimal)ItemTotal / PageLength) : 0); } } public uint ItemCount { get; set; } = 0; public uint ItemTotal { get; set; } = 0; } public PagingData Paging { get; private set; } public void SetPaging (uint pageNo, ushort pageLength, uint itemCount, uint itemTotal) { Paging = new PagingData() { PageNo = pageNo, PageLength = pageLength, ItemCount = itemCount, ItemTotal = itemTotal }; } } //------------------------------------------------------------------- // S e s s i o n C o n t e x t //------------------------------------------------------------------- protected OpnSessionContext GetSessionContext () { if (SessionData != null) return SessionData.SessionContext; Logger.Warn(GetType().Name + ".GetSessionContext() Session data is not available."); return null; } protected OpnSessionContext GetSessionContext (ushort index) { try { return App.GetSessionContextConfig(index).SessionContext; } catch (Exception exc) { Logger.Warn(GetType().Name + ".GetSessionContext(" + index + ") " + exc.GetType().Name + " - " + exc.Message + exc.GetStackEntries().Concat("", "\n\t")); } return null; } //------------------------------------------------------------------- // D a t a b a s e //------------------------------------------------------------------- private OpnSessionContext databaseSessionContext; private SacsDatabase database = null; protected SacsDatabase GetDatabase () { try { return GetDatabase(GetSessionContext()); } catch (Exception exc) { Logger.Warn(GetType().Name + ".GetDatabase() " + exc.GetType().Name + " - " + exc.Message + exc.GetStackEntries().Concat("", "\n\t")); } return null; } protected SacsDatabase GetDatabase (OpnSessionContext sessionContext) { if (databaseSessionContext != null && databaseSessionContext.Equals(sessionContext)) return database; try { database = App.GetSessionContextConfig(sessionContext.Index).Database; databaseSessionContext = sessionContext; } catch (Exception exc) { Logger.Warn(GetType().Name + ".GetDatabase(" + sessionContext.Index + "," + OpnSystem.GetInstanceCode(sessionContext.Instance) + ") " + exc.GetType().Name + " - " + exc.Message + exc.GetStackEntries().Concat("", "\n\t")); } return database; } //------------------------------------------------------------------- // Managers. //------------------------------------------------------------------- // Security console. private SaSecurityConsole securityConsole; protected SaSecurityConsole SecurityConsole { get { if (securityConsole == null) securityConsole = OpnGlobals.ConsoleHelper.GetSecurityConsole(GetSessionContext()); return securityConsole; } } // Code Type console. private SaCodeTypeConsole codeTypeConsole; protected SaCodeTypeConsole CodeTypeConsole { get { if (codeTypeConsole == null) codeTypeConsole = OpnGlobals.ConsoleHelper.GetCodeTypeConsole(GetSessionContext()); return codeTypeConsole; } } //------------------------------------------------------------------- // C o n s o l e s //------------------------------------------------------------------- //------------------------------------------------------------------- } //======================================================================= }