Conditional/limited access in a controller/view? (MVC2)
I have two roles being used on my site currently, author & admin. Authors cannot access user administration functions. However, they should be able to edit certain parts of their profile. An admin is currently able to edit all parts of a user's profile. For example:
employee ID [admin]
display name [author,admin]
roles [admin]
I would like to re-use code where possible. I'm not sure what the best solution would be here. There are 2 things to deal with
- Only allowing a user to edit their own profile and not others
- Restricting which fields that user can edit vs which fields an admin can edit
I think #1 is best achieved by a custom Authorize attribute (I already have one I can exte开发者_如何学JAVAnd further). If you have a better approach please share. And #2 I am unsure, view model? I have my allowed fields bound for a user using a partial class which would be different for each role.
Your solution for #1 is spot on, you need to use the AuthorizeAttribute
.
For #2 you can just do security trimming where you only render for the particular user.
Some pseudo code in your view (or move it to a partial view):
if administrator
render employee ID text box
if administrator || author
render display name text box
if administrator
render roles check list
So you're going to need to control how to determine if the user is in a "role". You can use ASP.NET's Membership Provider or roll something of your own.
精彩评论