In ASP.NET MVC, I hold in Session the user object with its privileges, so that I don't have to go to the database each time. So I'm using Session as a cache. eg:
When user logs in:
User user = dbContext.Users.Include(u => u.Privileges).SingleOrDefault(u => u.UserId == userId)
Session["CurrentUser"] = user;
When the user does future requests:
public ActionResult CreateSomething()
{
User user = Session["CurrentUser"];
if (user == null)
{
// Error: not logged in
}
if (!user.Privileges.Any(p => p.PrivilegeId == PrivilegesEnum.CreateSomething))
{
// Error: doesn't have privilege
}
...
}
As you can see, that ".Any(...)
" will work in memory, which is faster than going to the database.
The problem is that other users can revoke or add privileges to users that are already logged, and these already logged users will perceive these changes only the next time they log in.
public ActionResult RevokePrivilege(long targetUserId, long privilegeId)
{
...
targetUser.Privileges.Remove(privilege)
dbContext.SaveChanges();
// ... (*)
}
Question is: can I access other sessions in (*) so that I can do these changes in memory too?
Something like (I'm inventing here)
foreach (var kvp in SessionDictionary.Where(kvp => kvp.Value.UserId == user.UserId).ToList())
{
SessionDictionary[kvp.Key]["CurrentUser"].Privileges.Remove(privilege);
}