1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 2.0.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Auth;
16:
17: use Cake\Controller\ComponentRegistry;
18: use Cake\Controller\Controller;
19: use Cake\Core\Exception\Exception;
20: use Cake\Http\ServerRequest;
21:
22: /**
23: * An authorization adapter for AuthComponent. Provides the ability to authorize
24: * using a controller callback. Your controller's isAuthorized() method should
25: * return a boolean to indicate whether or not the user is authorized.
26: *
27: * ```
28: * public function isAuthorized($user)
29: * {
30: * if ($this->request->getParam('admin')) {
31: * return $user['role'] === 'admin';
32: * }
33: * return !empty($user);
34: * }
35: * ```
36: *
37: * The above is simple implementation that would only authorize users of the
38: * 'admin' role to access admin routing.
39: *
40: * @see \Cake\Controller\Component\AuthComponent::$authenticate
41: */
42: class ControllerAuthorize extends BaseAuthorize
43: {
44: /**
45: * Controller for the request.
46: *
47: * @var \Cake\Controller\Controller
48: */
49: protected $_Controller;
50:
51: /**
52: * {@inheritDoc}
53: */
54: public function __construct(ComponentRegistry $registry, array $config = [])
55: {
56: parent::__construct($registry, $config);
57: $this->controller($registry->getController());
58: }
59:
60: /**
61: * Get/set the controller this authorize object will be working with. Also
62: * checks that isAuthorized is implemented.
63: *
64: * @param \Cake\Controller\Controller|null $controller null to get, a controller to set.
65: * @return \Cake\Controller\Controller
66: * @throws \Cake\Core\Exception\Exception If controller does not have method `isAuthorized()`.
67: */
68: public function controller(Controller $controller = null)
69: {
70: if ($controller) {
71: if (!method_exists($controller, 'isAuthorized')) {
72: throw new Exception(sprintf(
73: '%s does not implement an isAuthorized() method.',
74: get_class($controller)
75: ));
76: }
77: $this->_Controller = $controller;
78: }
79:
80: return $this->_Controller;
81: }
82:
83: /**
84: * Checks user authorization using a controller callback.
85: *
86: * @param array|\ArrayAccess $user Active user data
87: * @param \Cake\Http\ServerRequest $request Request instance.
88: * @return bool
89: */
90: public function authorize($user, ServerRequest $request)
91: {
92: return (bool)$this->_Controller->isAuthorized($user);
93: }
94: }
95: