ControllerAuthorize.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * PHP 5
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Controller\Component\Auth;
  17. use Cake\Controller\ComponentRegistry;
  18. use Cake\Controller\Controller;
  19. use Cake\Error;
  20. use Cake\Network\Request;
  21. /**
  22. * An authorization adapter for AuthComponent. Provides the ability to authorize using a controller callback.
  23. * Your controller's isAuthorized() method should return a boolean to indicate whether or not the user is authorized.
  24. *
  25. * {{{
  26. * public function isAuthorized($user) {
  27. * if (!empty($this->request->params['admin'])) {
  28. * return $user['role'] === 'admin';
  29. * }
  30. * return !empty($user);
  31. * }
  32. * }}}
  33. *
  34. * the above is simple implementation that would only authorize users of the 'admin' role to access
  35. * admin routing.
  36. *
  37. * @since 2.0
  38. * @see AuthComponent::$authenticate
  39. */
  40. class ControllerAuthorize extends BaseAuthorize {
  41. /**
  42. * Get/set the controller this authorize object will be working with. Also checks that isAuthorized is implemented.
  43. *
  44. * @param Controller $controller null to get, a controller to set.
  45. * @return mixed
  46. * @throws Cake\Error\Exception
  47. */
  48. public function controller(Controller $controller = null) {
  49. if ($controller) {
  50. if (!method_exists($controller, 'isAuthorized')) {
  51. throw new Error\Exception(__d('cake_dev', '$controller does not implement an %s method.', 'isAuthorized()'));
  52. }
  53. }
  54. return parent::controller($controller);
  55. }
  56. /**
  57. * Checks user authorization using a controller callback.
  58. *
  59. * @param array $user Active user data
  60. * @param Cake\Network\Request $request
  61. * @return boolean
  62. */
  63. public function authorize($user, Request $request) {
  64. return (bool)$this->_Controller->isAuthorized($user);
  65. }
  66. }