Web-development – PHP MVC/PAC – Logged In/Admin checks placement

mvcmvpweb-applicationsweb-development

I have set-up a MVC/PAC-like structure for a web application (unsure if it fits any of these design patterns fully). In short it is:

  • Routing in index.php, which selects the controller and method using the URL http://example.com/controller/method/<params>
  • Controller's method requests data from 'model(s)' and assigns it to a view.

Now I am wondering what is the best spot for an logged in check. Let's say I have a page at http://example.com/controller-one/method-one/ which requires the user to be a logged in administrator; Where do I check whether the user actually is? In the routing, controller or model?

Please note that a controller and/or model might contain methods with different 'rights'.

Note: There is a model called Authentication which contains a method called isLogged() that returns true or false based on whether the user is logged in and another method which is called IsLoggedAdmin() which returns true or false based on whether the user is a logged in administrator.

So…: What is the best location to call the method isLogged or isLoggedAdmin. In the controller's contruct and/or method(s) or the model's contruct and/or method(s)?

Best Answer

Authentication should happen after routing but before calling controller or its methods.

At that point you know which route was requested and can check if user has privileges to perform a certain action (call controllers).

This allows not only to separate concerns, but also to decide how to handle unathorized requests before they hit controllers - eg. redirect them to other controller internally with 403 response.

Authentication/authorisation happens in higher layer than models. If they depend on user instances - you pass already authenticated/authorized instance. Also - when requirements change, and other roles are allowed to call previously prohibited methods - you change only ACLs and not models.

Symfony framework had a nice description how they did, it's still available for v.2: http://symfony.com/doc/2.0/book/security.html

Related Topic