CakePHP: How to use a function with a model in every controller?

I have a project which includes admin and user section. Both section use the same controllers, just different functions and templates (ex: viewAdmin() and viewUser()). In function beforeRender() of every controllers, I set variable $admin as true for admin functions and false for user functions.

For authentication, I use Shibboleth. Shibboleth uses data from LDAP, while user types were saved in SQL-Database, that means while it can check if the login and password are false, it can't check if the user is admin or not. An user can go to ADMIN section as long as they use the right action (ex: go to the link

To prevent this, I will have to:

  1. Load model Users
  2. Compare the environment variable uid (login name) with the "login" columns in Users table in my SQL-Database
  3. See the "type" column in Users table to know if user is admin or not.
  4. Compare the result with value of $admin and redirect to an error page when necessary.

The problem is: I don't want to repeat those steps for EVERY controllers.

Currently I have 2 ideas:

  1. Write a function in UsersController, and use it in every controllers.
  2. Create a component and load it in every controllers.

Both methods require me changing code in all controllers. I would like to hear a better way with less work, perhaps by changing app.php or bootstrap.php.

Any suggestion is appreciated.

1 answer

  • answered 2019-06-25 22:08 Salines

    To share methods in CakePHP controllers you can do:

    1. Create component and include in controller
    2. Or create method in AppController and use it in child controllers
    3. Or PHP way create Trait.

    But when you authorize users, then all user data is stored in session, incl. is user roles (example admin, regular, member,.. )