views:

61

answers:

1

Basically I'm writing my own version of a 'RoleProvider' and 'AuthorizeAttribute'. I've got an Enum (as a bit field) with a list of all possible roles:

namespace myProject.Global
{
    [Flags]
    enum Roles
    {
        Viewer = 1,
        User = 2,
        Admin = 4,
        Superadmin = 8
    }
}

My AuthorizeAttribute works similarly to the existing one. In my logic, I loop through each 'Authorized' role and check to see if the user belongs to it. *rolesSplit is an array of the roles provided in the AuthorizeAttribute for a particular action. httpContext.Session["Roles"] is an integer representing the user's roles.

 foreach (string roleName in _rolesSplit)
{
    if ((httpContext.Session["Roles"] & myProject.Global.Roles[roleName]) == myProject.Global.Roles[roleName]) return true;
}

return false;

This is the part I can't get working: APICText.Global.Roles[roleName]. I'm new to .NET development so I'm not sure how to make this work. I basically need to pass something the role name and get the associated value back. How do I do this?

+3  A: 

What you need is Enum.Parse.

Try something like this...

foreach (string roleName in _rolesSplit)
{
    if (httpContext.Session["Roles"] & (Roles)Enum.Parse(typeof(Roles), roleName) == (Roles)Enum.Parse(typeof(Roles), roleName)) return true;
}

or this...

foreach (string roleName in _rolesSplit)
{
    Roles role = (Roles)Enum.Parse(typeof(Roles), roleName);
    if (httpContext.Session["Roles"] & role == role) return true;
}
Scott Ivey
Thanks for the help! I was able to get this code working, although another bug in my code is preventing me from testing it right now.Coming from PHP, the idea of strongly-typed objects/variables is still kinda new to me, definitely has major advantages when you know how to use it =]Thanks again, I really appreciate it!!
Colin O'Dell