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: /**
46: * Controller for the request.
47: *
48: * @var \Cake\Controller\Controller
49: */
50: protected $_Controller;
51:
52: /**
53: * {@inheritDoc}
54: */
55: public function __construct(ComponentRegistry $registry, array $config = [])
56: {
57: parent::__construct($registry, $config);
58: $this->controller($registry->getController());
59: }
60:
61: /**
62: * Get/set the controller this authorize object will be working with. Also
63: * checks that isAuthorized is implemented.
64: *
65: * @param \Cake\Controller\Controller|null $controller null to get, a controller to set.
66: * @return \Cake\Controller\Controller
67: * @throws \Cake\Core\Exception\Exception If controller does not have method `isAuthorized()`.
68: */
69: public function controller(Controller $controller = null)
70: {
71: if ($controller) {
72: if (!method_exists($controller, 'isAuthorized')) {
73: throw new Exception(sprintf(
74: '%s does not implement an isAuthorized() method.',
75: get_class($controller)
76: ));
77: }
78: $this->_Controller = $controller;
79: }
80:
81: return $this->_Controller;
82: }
83:
84: /**
85: * Checks user authorization using a controller callback.
86: *
87: * @param array|\ArrayAccess $user Active user data
88: * @param \Cake\Http\ServerRequest $request Request instance.
89: * @return bool
90: */
91: public function authorize($user, ServerRequest $request)
92: {
93: return (bool)$this->_Controller->isAuthorized($user);
94: }
95: }
96: