Question

This is the basic database structure for Users and UserRoles.

enter image description here

My client wants to be able to look at a Role and tick some boxes, "This role can do x, y and z". X, Y and Z being some actions in the application.

This isn't a new idea, and I'm sure there is a proven pattern for this situation. Similar to what Wordpress does, it selects functions a role Foo can perform, and a User belongs to that Role.

Any suggestions on an MVC3 specific solution?

Was it helpful?

Solution

The built in Attribute [Authorize] lets you restrict certain actions so that can be only performed by certain roles.

For what you are trying to, I'd suggest that treat 'Functions X,Y and Z' as the roles, and that you treat what you currently have as roles as 'user groups' or something. So, your client then would be able to assign different 'User Groups' access to certain 'Roles'.

This way you could make use of the built in membership/role/authorization stuff. all you'd need to do was implement your own MembershipProvider and RoleProvider.

Your role providers implementation of string[] GetRolesForUser(string username) would need to do a database look up to see what 'User group(s)' they are in, and therefore which 'Role(s)' they have access to.

If you do that, you can easily restrict access to the different functions via the [Authorize] attribute, and use the standard membership stuff for handling the login process.

If your client insists on calling them 'Roles' and 'Functions' rather than 'User Groups' and 'Roles' - you don't need to tell him that this is not quite how you've implemented it :)

Edit

Alternatively, you can create your own Authorization attibute, just derive from AuthorizeAttribute, and override AuthorizeCore( HttpContextBase httpContext) return true or false if the user is in a role permitted do do function 'X'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top