Where do we handle permissions in MVC? At the Controller or Model level?
I'm tinkering with Play! java framework and trying to understand MVC.
Consider this scenario: A blogging app has moderators and users, and both can update posts. Moderators' updates are immediately saved. Users' updates are queued to be approved by a moderator. In MVC, where do we put the logic to determine whether to update or queue the updates?
One way to do it is in the Controller (pseudo-code):
public void function update() {
User user = User.find开发者_如何学运维("byEmail");
if ( user.isModerator() ) {
post.update( args );
}
else {
// save post in a temporary table where it awaits approval.
}
}
Am I right in using this approach or are there better alternatives?
I know that this is quite an old question, but I had the same - so this might be of help:
In my current project, the policy is to layer the authorisation checks. This way, the checks will be done where they fit best:
- if it is important for consistancy of the data, checks are done in the model (very rare cases, needs to be set in the API documentation!).
- most checks are done at controller level, so most checks are in a single place.
- some checks are done in the "View" (this means they controll the JSON output of an API, and this in turn changes behaviour in the front end). These are quite rare, as these are mostly based on data fed from the controller and not querying the user's permissions directly.
I came up with that solution after reading this post. It provides a good summary on why using the controller is a good idea - and what the alternatives are.
The main reason, why I chose the controller as a place for authorisation checks is that it allows the model (and the data it manages) to be independent of application logic - which includes authorisation.
Please keep in mind, that this is totally dependent on what you want to achieve. I just wanted to show what works for me.
精彩评论