Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.