Files
BeWoPlaner/BeWoPlanerMobil/Service/ASPHibernateSessionManager.cs

199 lines
6.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Configuration;
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.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 log4net.ILog Log = log4net.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("");
serverPath = Path.Combine(serverPath, ConfigurationManager.AppSettings.Get("MultitenancyPath"));
serverPath = Path.Combine(serverPath, MobileSessionFacade.Tenant + ".config");
if(!File.Exists(serverPath))
{
return null;
}
SessionFactories[MobileSessionFacade.Tenant] = new Configuration().Configure(serverPath).SetInterceptor(new MobileUpdInsInterceptor()).BuildSessionFactory();
}
return SessionFactories[MobileSessionFacade.Tenant];
}
catch(Exception e)
{
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 == null)
{
return;
}
// ---------------------------------------------------------------
if(!ConfigureHibernateSession())
{
return;
}
var userLoaded = TryAuthenticateWithLoginForm(context);
if(!userLoaded && MobileSessionFacade.LoggedInUser != null && MobileSessionFacade.LoggedInUser.Oid.HasValue)
{
MobileSessionFacade.LoggedInUser = DAOFactory.GenericDAO.LoadByID<ApplicationUser>(MobileSessionFacade.LoggedInUser.Oid.Value);
}
}
};
context.EndRequest += (s, e) =>
{
if(HttpContext.Current.Items["hibernateSession"] != null)
{
((ISession)HttpContext.Current.Items["hibernateSession"]).Close();
HttpContext.Current.Items.Remove("hibernateSession");
}
};
}
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"];
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;
}
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.LoggedInUser = user;
}
return true;
}
public static bool ConfigureHibernateSessionForWebService()
{
return ConfigureHibernateSession();
}
}
}