1. Backstory
I recently starting programming and I found out that Entity Framework works perfect for my small-sized applications due its simplicity.
I've made my custom authorize attribute for MVC controllers and controller methods to check if the current user has a certain role (which is an enum type in my case).
The following code represents my authorize attribute:
public class HasRoleAttribute : ActionFilterAttribute
{
private Role _role;
public HasRoleAttribute(Role role)
{
this._role = role;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var context = new FactoryManagementContext();
var userName = filterContext.HttpContext.User.Identity.Name;
var user = context.Users.FirstOrDefault(item => item.UserName == userName);
var hasRole = user.Role == _role;
if (user == null || !hasRole)
{
// If this user does not have the
// required permission then redirect to login page
var url = new UrlHelper(filterContext.RequestContext);
var loginUrl = url.Content("/Account/Login");
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
public enum Role
{
Engineer,
Manager,
Admin
}
2. Question
It works as a charm, but I have only one question: is it necessary to initialize the database context every single time when authorizing a user?