Created
January 13, 2018 04:54
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UserFilter: ActionFilterAttribute | |
{ | |
/// | |
/// Set session data for current user: | |
/// - Current user | |
/// - Tenant of the current user | |
/// | |
/// | |
public override void OnActionExecuting(ActionExecutingContext filterContext) { | |
// User must be logged in before setting session data | |
if (filterContext.HttpContext.User.Identity.IsAuthenticated) | |
{ | |
// Ensure session data compares to the actual current user | |
if (filterContext.HttpContext.Session["User"] as string != filterContext.HttpContext.User.Identity.Name) | |
{ | |
filterContext.HttpContext.Session["User"] = filterContext.HttpContext.User.Identity.Name; | |
filterContext.HttpContext.Session["Tenant"] = null; | |
} | |
// Set tenancy identity for the current user | |
if (filterContext.HttpContext.Session["Tenant"] == null) | |
{ | |
string directoryPath = filterContext.HttpContext.Server.MapPath("~/bin"); | |
using(ServiceFactory factory = new ServiceFactory(directoryPath)) | |
{ | |
string[, ] nullconstructor = new string[, ] { | |
{ | |
"Tenant", | |
null | |
} | |
}; | |
using(IRepository tenantRepository = factory.Create(nullconstructor)) | |
{ | |
// Get current user from database and check to which tenant it belongs | |
m.Tenant currentTenant = tenantRepository.FindOne(x = & gt; x.AspNetUsers.Select(y = & gt; y.Email).Contains(filterContext.HttpContext.User.Identity.Name)); | |
string tenantCode = currentTenant != null ? currentTenant.Code : string.Empty; | |
filterContext.HttpContext.Session["Tenant"] = tenantCode; | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment