views:

132

answers:

2

At which layer (Model, View, Controller) of MVC should permission logic be handled?

Let me clarify that a bit. Obviously the UI (View and Controller) need to be able to access permissions to show/hide components and to handle the permission denied scenario. It also seems obvious that the permissions should be persisted to the database by the Model layer.

But what about "complex" permission rules like this?
In a wiki/CMS system I'm developing, each user has a set of per-page permissions (view, edit, rename, etc.). For existing pages, these permissions are retrieved from the database. For a new page, the user is assumed to have all possible permissions (as they create/edit it).

Another example would be the list of pages:
The current user should only be able to see pages which they have view permission on in the list of pages.

Should the Controller handle this logic? Or should the Controller only be responsible for calling a GetPermissions() method (or GetPageList), and all the logic for populating it be handled in the Model?

+1  A: 

The model should have the information about the allowed/denied permissions for the logged-in user. Then controller should allow/block actions according to the model. At the same time, the view should only paint links corresponding to actions the user will be allowed to execute. The view will know whether to paint or not a certain link asking the model (once again).

You must use defensive programming: if you don't control access to action on controller, not painting a link for a given user, still allows that user to execute an action. On the other hand, painting a link of an action that will crash (if only checking permissions on controller) will annoy your users.

ignasi35
+2  A: 

Control of access to problem-domain entities belongs in the model. It's the appropriate place because (1) access control to domain entities is closely tied to the entities themselves, and (2) that's the one place you can ensure no two controllers allow different access policies to the same objects.

The following factors add some confusion:

  1. Authentication occurs at the controller level
  2. Some tools and demos are available for applying access control easily -- at the controller layer, e.g. this, this or that.

It still belongs at the model though.

Oren Trutner