There's no built-in way to check if a user is in multiple roles, but it's pretty trivial to create a nice extension method to handle it for you:
public static bool IsInAnyRole(this IPrincipal principal, params string[] roles)
{
return roles.Any(principal.IsInRole);
}
Usage then is:
if (User.IsInAnyRole("Admin", "Author", "SuperUser"))
{
}
EDIT: Without coding each role, do it a LINQ extension method, like so:
private static bool IsInAnyRole(this IPrincipal user, List<string> roles)
{
var userRoles = Roles.GetRolesForUser(user.Identity.Name);
return userRoles.Any(u => roles.Contains(u));
}
For usage, do:
var roles = new List<string> { "Admin", "Author", "Super" };
if (user.IsInAnyRole(roles))
{
//do something
}
Or without the extension method:
var roles = new List<string> { "Admin", "Author", "Super" };
var userRoles = Roles.GetRolesForUser(User.Identity.Name);
if (userRoles.Any(u => roles.Contains(u))
{
//do something
}
You can also use
if(Roles.GetRolesForUser(model.UserName).Contains("Admin")){
}
I wanted to elaborate a little on mattytommo's answer, here is what I use:
Extension Method:
public static bool IsInAnyRole(this IPrincipal user, string[] roles)
{
//Check if authenticated first (optional)
if (!user.Identity.IsAuthenticated) return false;
var userRoles = Roles.GetRolesForUser(user.Identity.Name);
return userRoles.Any(roles.Contains);
}
Constants:
public static class Role
{
public const string Administrator = "Administrator";
public const string Moderator = "Moderator";
}
Usage:
if (User.IsInAnyRole(new [] {Role.Administrator,Role.Moderator}))
{
//Do stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With