Regardless of the language or MVC framework used, how should I handle different views based on roles?
For example (pseudo code):
<% show post here %>
if (role.isAdmin or role.isModerator) {
<% show moderation tools %>
}
<% show rest of content %>
I don't quite like the idea of putting too much business logic into the view, but it doesn't seem like there're other options. Are there?
This gets messier and messier once you have more roles, or different levels of permissions. Take this site for example. Users with more than 200 rep see less ads. Users with more than 500 rep have a retag button. Then you get an edit button at 2000, a close button at 3000, moderation tools at 10k, and more functions if you are a "star" moderator.
You can make this a little neater by having a custom ViewModel with a boolean property called ShowModerationTools
. In your controller you perform the checks to see whether the current user, based on their roles, can see the post and set ShowModerationTools
to either true
or false
. You then return the custom ViewModel to the view. That way you can then just do this in your view:
<% show post here %>
if (Model.ShowModerationTools) {
<% show moderation tools %>
}
<% show rest of content %>
It also means if your business rules change (for instance you need to introduce another condition) you just change the controller and don't need to alter your view.