Files
BeWoPlaner/BeWoPlanerMobil/Service/ASPHibernateSessionManager.cs
2025-09-09 10:27:54 +02:00

236 lines
8.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.ServiceModel;
using System.Threading;
using System.Web;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.DCEntityMapper;
using BeWo.Service.ServiceImplementations;
using BeWoPlanerMobil.Util;
using BS.Shared;
using BS.Shared.Core;
using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;
using NHibernate;
using Configuration = NHibernate.Cfg.Configuration;
namespace BeWoPlanerMobil.Service
{
public class ASPHibernateSessionManager : IHttpModule
{
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Dictionary<string, ISessionFactory> SessionFactories = new Dictionary<string, ISessionFactory>();
private static readonly object _Lock = string.Empty;
private static ISessionFactory SessionFactory
{
get
{
try
{
Monitor.Enter(_Lock);
if(!SessionFactories.ContainsKey(MobileSessionFacade.Tenant))
{
#if DEBUG
var hierarchy = (Hierarchy)LogManager.GetRepository();
var logger = (Logger)hierarchy.GetLogger("NHibernate.SQL");
logger.AddAppender(new TraceAppender { Layout = new SimpleLayout() });
hierarchy.Configured = true;
#endif
var serverPath = HttpContext.Current.Server.MapPath(null);
var multitenancyPath = ConfigurationManager.AppSettings.Get("MultitenancyPath");
var configFileName = $"{MobileSessionFacade.Tenant}.config";
serverPath = Path.Combine(serverPath, multitenancyPath);
serverPath = Path.Combine(serverPath, configFileName);
if(!File.Exists(serverPath))
{
serverPath = HttpContext.Current.Server.MapPath(null);
serverPath = Path.Combine(serverPath, Path.Combine("..\\", Path.Combine(multitenancyPath, configFileName)));
if(!File.Exists(serverPath))
{
serverPath = HttpContext.Current.Server.MapPath(null);
serverPath = Path.Combine(serverPath, Path.Combine(@"..\..\", Path.Combine(multitenancyPath, configFileName)));
if(!File.Exists(serverPath))
{
return null;
}
}
}
var config = new Configuration().Configure(serverPath).SetInterceptor(new MobileUpdInsInterceptor()).BuildSessionFactory();
SessionFactories[MobileSessionFacade.Tenant] = config;
}
return SessionFactories[MobileSessionFacade.Tenant];
}
catch(Exception e)
{
Debug.WriteLine($"{DateTime.Now:dd.MM.yyyy HH:mm:ss.fff}: Fehler bei SessionFactory-Get: {e.Message}");
throw new FaultException(e.StackTrace + (e.InnerException?.Message ?? string.Empty));
}
finally
{
Monitor.Exit(_Lock);
}
}
}
public void Dispose() {}
public void Init(HttpApplication context)
{
context.AcquireRequestState += (s, e) =>
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
if(ShouldConfigureHibernateSession(context))
{
// TEST FOR DEVEXPRESS. PROBLEMS WITH THIS MODULE WHEN USING AJAX!
if(HttpContext.Current.Session is null)
{
return;
}
// ---------------------------------------------------------------
if(!ConfigureHibernateSession())
{
return;
}
var userLoaded = TryAuthenticateWithLoginForm(context);
//if (!userLoaded && MobileSessionFacade.IsUserLoggedIn())
//{
// MobileSessionFacade.LogUserOut();
//}
//if(!userLoaded && MobileSessionFacade.LoggedInUser != null && MobileSessionFacade.LoggedInUser.UserOid.HasValue)
//{
// MobileSessionFacade.LoggedInUser = MapperFactory.UserDC_User.MapToNewDC(DAOFactory.GenericDAO.LoadByID<ApplicationUser>(MobileSessionFacade.LoggedInUser.UserOid.Value));
//}
}
};
context.EndRequest += (s, e) =>
{
if(HttpContext.Current.Items["hibernateSession"] is null)
{
//Debug.WriteLine($"++++>{DateTime.Now:dd.MM.yyyy HH:mm:ss.fff}: Beende Anfrage; Sitzung ist null!");
return;
}
((ISession)HttpContext.Current.Items["hibernateSession"]).Close();
HttpContext.Current.Items.Remove("hibernateSession");
//Debug.WriteLine($"####>{DateTime.Now:dd.MM.yyyy HH:mm:ss.fff}: Beende Anfrage; schließe und entferne Sitzung!");
};
}
private static bool ShouldConfigureHibernateSession(HttpApplication context)
{
if(context.Request.FilePath.IndexOf("/Chat/", StringComparison.InvariantCulture) >= 0)
{
return false;
}
return string.IsNullOrEmpty(context.Request.FilePath) || context.Request.FilePath.IndexOf("Admin.aspx", StringComparison.InvariantCulture) < 0;
}
private static bool ConfigureHibernateSession()
{
var tenant = MobileSessionFacade.Tenant;
if(string.IsNullOrEmpty(tenant))
{
//TODO: ist bei showPin=1 null!
tenant = HttpContext.Current.Request.Params["tb_tenant"];
if (!String.IsNullOrEmpty(tenant))
{
tenant = tenant.Trim();
}
MobileSessionFacade.Tenant = tenant;
}
if(string.IsNullOrEmpty(tenant))
{
return false;
}
if(SessionFactory != null)
{
HttpContext.Current.Items.Add("hibernateSession", SessionFactory.OpenSession());
return true;
}
return false;
}
private static bool TryAuthenticateWithLoginForm(HttpApplication context)
{
var name = context.Request.Params["tb_login"];
var password = context.Request.Params["tb_password"];
var tenant = context.Request.Params["tb_tenant"];
var pin = context.Request.Params["tb_pin"];
if (Utils.IsAnyNullOrEmpty(name, password, tenant))
{
return false;
}
tenant = tenant.Trim();
if (pin != null)
{
var browserType = context.Request.Browser.Type;
var browserPlatform = context.Request.Browser.Platform;
pin += "_" + browserType + "_" + browserPlatform;
}
MobileSessionFacade.Tenant = tenant;
var userService = new UserServiceImp();
Log.Info($"TryAuthenticateWithLoginForm with username: '{name}', Tenant: {MobileSessionFacade.Tenant}, PIN: {pin}");
if(userService.IsUserValid(name, password, pin, "MobilClient", false, "") == UserValidationResult.UserValid)
{
var user = DAOFactory.UserDAO.FindUserByLoginName(name);
if(user is null || !DAOFactory.UserDAO.CheckPassword(user, password))
{
return false;
}
MobileSessionFacade.PasswordStrength = new PasswordUtils().EvaluatePasswordStrength(password);
MobileSessionFacade.LoggedInUserOid = user.Oid;
MobileSessionFacade.EmployeeFullname = user.Employee.Person.FirstNameLastName;
//MobileSessionFacade.LoggedInEmployee = MapperFactory.EmployeeDC_Employee.MapToNewDC(user.Employee);
}
return true;
}
public static bool ConfigureHibernateSessionForWebService()
{
return ConfigureHibernateSession();
}
}
}