简体   繁体   中英

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 http://example.com/tool/viewAdmin ).

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.

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,.. )

Use the official CakePHP authentication plugin and extend the LDAP adapter with the additional code check you need. This is very easy to do and also a very clean way of solving the problem. Disclaimer: I'm one of the authors of the authentication plugin. https://github.com/cakephp/authentication

Or if you want to stay agnostic to any framework, use my library that is based on the authentication plugin and was decoupled from any framework but still works just nice with Cake https://github.com/Phauthentic/authentication .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM