Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hbulens/f3f198f16a96576768e84cebd3ae0af4 to your computer and use it in GitHub Desktop.
Save hbulens/f3f198f16a96576768e84cebd3ae0af4 to your computer and use it in GitHub Desktop.
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