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 0.10.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Controller\Component;
16:
17: use Cake\Auth\Storage\StorageInterface;
18: use Cake\Controller\Component;
19: use Cake\Controller\Controller;
20: use Cake\Core\App;
21: use Cake\Core\Exception\Exception;
22: use Cake\Event\Event;
23: use Cake\Event\EventDispatcherTrait;
24: use Cake\Http\Exception\ForbiddenException;
25: use Cake\Http\Response;
26: use Cake\Http\ServerRequest;
27: use Cake\Routing\Router;
28: use Cake\Utility\Hash;
29:
30: /**
31: * Authentication control component class.
32: *
33: * Binds access control with user authentication and session management.
34: *
35: * @property \Cake\Controller\Component\RequestHandlerComponent $RequestHandler
36: * @property \Cake\Controller\Component\FlashComponent $Flash
37: * @link https://book.cakephp.org/3.0/en/controllers/components/authentication.html
38: */
39: class AuthComponent extends Component
40: {
41:
42: use EventDispatcherTrait;
43:
44: /**
45: * The query string key used for remembering the referrered page when getting
46: * redirected to login.
47: */
48: const QUERY_STRING_REDIRECT = 'redirect';
49:
50: /**
51: * Constant for 'all'
52: *
53: * @var string
54: */
55: const ALL = 'all';
56:
57: /**
58: * Default config
59: *
60: * - `authenticate` - An array of authentication objects to use for authenticating users.
61: * You can configure multiple adapters and they will be checked sequentially
62: * when users are identified.
63: *
64: * ```
65: * $this->Auth->setConfig('authenticate', [
66: * 'Form' => [
67: * 'userModel' => 'Users.Users'
68: * ]
69: * ]);
70: * ```
71: *
72: * Using the class name without 'Authenticate' as the key, you can pass in an
73: * array of config for each authentication object. Additionally you can define
74: * config that should be set to all authentications objects using the 'all' key:
75: *
76: * ```
77: * $this->Auth->setConfig('authenticate', [
78: * AuthComponent::ALL => [
79: * 'userModel' => 'Users.Users',
80: * 'scope' => ['Users.active' => 1]
81: * ],
82: * 'Form',
83: * 'Basic'
84: * ]);
85: * ```
86: *
87: * - `authorize` - An array of authorization objects to use for authorizing users.
88: * You can configure multiple adapters and they will be checked sequentially
89: * when authorization checks are done.
90: *
91: * ```
92: * $this->Auth->setConfig('authorize', [
93: * 'Crud' => [
94: * 'actionPath' => 'controllers/'
95: * ]
96: * ]);
97: * ```
98: *
99: * Using the class name without 'Authorize' as the key, you can pass in an array
100: * of config for each authorization object. Additionally you can define config
101: * that should be set to all authorization objects using the AuthComponent::ALL key:
102: *
103: * ```
104: * $this->Auth->setConfig('authorize', [
105: * AuthComponent::ALL => [
106: * 'actionPath' => 'controllers/'
107: * ],
108: * 'Crud',
109: * 'CustomAuth'
110: * ]);
111: * ```
112: *
113: * - ~~`ajaxLogin`~~ - The name of an optional view element to render when an Ajax
114: * request is made with an invalid or expired session.
115: * **This option is deprecated since 3.3.6.** Your client side code should
116: * instead check for 403 status code and show appropriate login form.
117: *
118: * - `flash` - Settings to use when Auth needs to do a flash message with
119: * FlashComponent::set(). Available keys are:
120: *
121: * - `key` - The message domain to use for flashes generated by this component,
122: * defaults to 'auth'.
123: * - `element` - Flash element to use, defaults to 'default'.
124: * - `params` - The array of additional params to use, defaults to ['class' => 'error']
125: *
126: * - `loginAction` - A URL (defined as a string or array) to the controller action
127: * that handles logins. Defaults to `/users/login`.
128: *
129: * - `loginRedirect` - Normally, if a user is redirected to the `loginAction` page,
130: * the location they were redirected from will be stored in the session so that
131: * they can be redirected back after a successful login. If this session value
132: * is not set, redirectUrl() method will return the URL specified in `loginRedirect`.
133: *
134: * - `logoutRedirect` - The default action to redirect to after the user is logged out.
135: * While AuthComponent does not handle post-logout redirection, a redirect URL
136: * will be returned from `AuthComponent::logout()`. Defaults to `loginAction`.
137: *
138: * - `authError` - Error to display when user attempts to access an object or
139: * action to which they do not have access.
140: *
141: * - `unauthorizedRedirect` - Controls handling of unauthorized access.
142: *
143: * - For default value `true` unauthorized user is redirected to the referrer URL
144: * or `$loginRedirect` or '/'.
145: * - If set to a string or array the value is used as a URL to redirect to.
146: * - If set to false a `ForbiddenException` exception is thrown instead of redirecting.
147: *
148: * - `storage` - Storage class to use for persisting user record. When using
149: * stateless authenticator you should set this to 'Memory'. Defaults to 'Session'.
150: *
151: * - `checkAuthIn` - Name of event for which initial auth checks should be done.
152: * Defaults to 'Controller.startup'. You can set it to 'Controller.initialize'
153: * if you want the check to be done before controller's beforeFilter() is run.
154: *
155: * @var array
156: */
157: protected $_defaultConfig = [
158: 'authenticate' => null,
159: 'authorize' => null,
160: 'ajaxLogin' => null,
161: 'flash' => null,
162: 'loginAction' => null,
163: 'loginRedirect' => null,
164: 'logoutRedirect' => null,
165: 'authError' => null,
166: 'unauthorizedRedirect' => true,
167: 'storage' => 'Session',
168: 'checkAuthIn' => 'Controller.startup'
169: ];
170:
171: /**
172: * Other components utilized by AuthComponent
173: *
174: * @var array
175: */
176: public $components = ['RequestHandler', 'Flash'];
177:
178: /**
179: * Objects that will be used for authentication checks.
180: *
181: * @var \Cake\Auth\BaseAuthenticate[]
182: */
183: protected $_authenticateObjects = [];
184:
185: /**
186: * Objects that will be used for authorization checks.
187: *
188: * @var \Cake\Auth\BaseAuthorize[]
189: */
190: protected $_authorizeObjects = [];
191:
192: /**
193: * Storage object.
194: *
195: * @var \Cake\Auth\Storage\StorageInterface|null
196: */
197: protected $_storage;
198:
199: /**
200: * Controller actions for which user validation is not required.
201: *
202: * @var array
203: * @see \Cake\Controller\Component\AuthComponent::allow()
204: */
205: public $allowedActions = [];
206:
207: /**
208: * Request object
209: *
210: * @var \Cake\Http\ServerRequest
211: */
212: public $request;
213:
214: /**
215: * Response object
216: *
217: * @var \Cake\Http\Response
218: */
219: public $response;
220:
221: /**
222: * Instance of the Session object
223: *
224: * @var \Cake\Http\Session
225: * @deprecated 3.1.0 Will be removed in 4.0
226: */
227: public $session;
228:
229: /**
230: * The instance of the Authenticate provider that was used for
231: * successfully logging in the current user after calling `login()`
232: * in the same request
233: *
234: * @var \Cake\Auth\BaseAuthenticate|null
235: */
236: protected $_authenticationProvider;
237:
238: /**
239: * The instance of the Authorize provider that was used to grant
240: * access to the current user to the URL they are requesting.
241: *
242: * @var \Cake\Auth\BaseAuthorize|null
243: */
244: protected $_authorizationProvider;
245:
246: /**
247: * Initialize properties.
248: *
249: * @param array $config The config data.
250: * @return void
251: */
252: public function initialize(array $config)
253: {
254: $controller = $this->_registry->getController();
255: $this->setEventManager($controller->getEventManager());
256: $this->response =& $controller->response;
257: $this->session = $controller->getRequest()->getSession();
258:
259: if ($this->getConfig('ajaxLogin')) {
260: deprecationWarning(
261: 'The `ajaxLogin` option is deprecated. Your client-side ' .
262: 'code should instead check for 403 status code and show ' .
263: 'appropriate login form.'
264: );
265: }
266: }
267:
268: /**
269: * Callback for Controller.startup event.
270: *
271: * @param \Cake\Event\Event $event Event instance.
272: * @return \Cake\Http\Response|null
273: */
274: public function startup(Event $event)
275: {
276: return $this->authCheck($event);
277: }
278:
279: /**
280: * Main execution method, handles initial authentication check and redirection
281: * of invalid users.
282: *
283: * The auth check is done when event name is same as the one configured in
284: * `checkAuthIn` config.
285: *
286: * @param \Cake\Event\Event $event Event instance.
287: * @return \Cake\Http\Response|null
288: * @throws \ReflectionException
289: */
290: public function authCheck(Event $event)
291: {
292: if ($this->_config['checkAuthIn'] !== $event->getName()) {
293: return null;
294: }
295:
296: /** @var \Cake\Controller\Controller $controller */
297: $controller = $event->getSubject();
298:
299: $action = strtolower($controller->getRequest()->getParam('action'));
300: if (!$controller->isAction($action)) {
301: return null;
302: }
303:
304: $this->_setDefaults();
305:
306: if ($this->_isAllowed($controller)) {
307: return null;
308: }
309:
310: $isLoginAction = $this->_isLoginAction($controller);
311:
312: if (!$this->_getUser()) {
313: if ($isLoginAction) {
314: return null;
315: }
316: $result = $this->_unauthenticated($controller);
317: if ($result instanceof Response) {
318: $event->stopPropagation();
319: }
320:
321: return $result;
322: }
323:
324: if ($isLoginAction ||
325: empty($this->_config['authorize']) ||
326: $this->isAuthorized($this->user())
327: ) {
328: return null;
329: }
330:
331: $event->stopPropagation();
332:
333: return $this->_unauthorized($controller);
334: }
335:
336: /**
337: * Events supported by this component.
338: *
339: * @return array
340: */
341: public function implementedEvents()
342: {
343: return [
344: 'Controller.initialize' => 'authCheck',
345: 'Controller.startup' => 'startup',
346: ];
347: }
348:
349: /**
350: * Checks whether current action is accessible without authentication.
351: *
352: * @param \Cake\Controller\Controller $controller A reference to the instantiating
353: * controller object
354: * @return bool True if action is accessible without authentication else false
355: */
356: protected function _isAllowed(Controller $controller)
357: {
358: $action = strtolower($controller->getRequest()->getParam('action'));
359:
360: return in_array($action, array_map('strtolower', $this->allowedActions));
361: }
362:
363: /**
364: * Handles unauthenticated access attempt. First the `unauthenticated()` method
365: * of the last authenticator in the chain will be called. The authenticator can
366: * handle sending response or redirection as appropriate and return `true` to
367: * indicate no further action is necessary. If authenticator returns null this
368: * method redirects user to login action. If it's an AJAX request and config
369: * `ajaxLogin` is specified that element is rendered else a 403 HTTP status code
370: * is returned.
371: *
372: * @param \Cake\Controller\Controller $controller A reference to the controller object.
373: * @return \Cake\Http\Response|null Null if current action is login action
374: * else response object returned by authenticate object or Controller::redirect().
375: * @throws \Cake\Core\Exception\Exception
376: */
377: protected function _unauthenticated(Controller $controller)
378: {
379: if (empty($this->_authenticateObjects)) {
380: $this->constructAuthenticate();
381: }
382: $response = $this->response;
383: $auth = end($this->_authenticateObjects);
384: if ($auth === false) {
385: throw new Exception('At least one authenticate object must be available.');
386: }
387: $result = $auth->unauthenticated($controller->getRequest(), $response);
388: if ($result !== null) {
389: return $result;
390: }
391:
392: if (!$controller->getRequest()->is('ajax')) {
393: $this->flash($this->_config['authError']);
394:
395: return $controller->redirect($this->_loginActionRedirectUrl());
396: }
397:
398: if (!empty($this->_config['ajaxLogin'])) {
399: $controller->viewBuilder()->setTemplatePath('Element');
400: $response = $controller->render(
401: $this->_config['ajaxLogin'],
402: $this->RequestHandler->ajaxLayout
403: );
404: }
405:
406: return $response->withStatus(403);
407: }
408:
409: /**
410: * Returns the URL of the login action to redirect to.
411: *
412: * This includes the redirect query string if applicable.
413: *
414: * @return array|string
415: */
416: protected function _loginActionRedirectUrl()
417: {
418: $urlToRedirectBackTo = $this->_getUrlToRedirectBackTo();
419:
420: $loginAction = $this->_config['loginAction'];
421: if ($urlToRedirectBackTo === '/') {
422: return $loginAction;
423: }
424:
425: if (is_array($loginAction)) {
426: $loginAction['?'][static::QUERY_STRING_REDIRECT] = $urlToRedirectBackTo;
427: } else {
428: $char = strpos($loginAction, '?') === false ? '?' : '&';
429: $loginAction .= $char . static::QUERY_STRING_REDIRECT . '=' . urlencode($urlToRedirectBackTo);
430: }
431:
432: return $loginAction;
433: }
434:
435: /**
436: * Normalizes config `loginAction` and checks if current request URL is same as login action.
437: *
438: * @param \Cake\Controller\Controller $controller A reference to the controller object.
439: * @return bool True if current action is login action else false.
440: */
441: protected function _isLoginAction(Controller $controller)
442: {
443: $uri = $controller->request->getUri();
444: $url = Router::normalize($uri->getPath());
445: $loginAction = Router::normalize($this->_config['loginAction']);
446:
447: return $loginAction === $url;
448: }
449:
450: /**
451: * Handle unauthorized access attempt
452: *
453: * @param \Cake\Controller\Controller $controller A reference to the controller object
454: * @return \Cake\Http\Response
455: * @throws \Cake\Http\Exception\ForbiddenException
456: */
457: protected function _unauthorized(Controller $controller)
458: {
459: if ($this->_config['unauthorizedRedirect'] === false) {
460: throw new ForbiddenException($this->_config['authError']);
461: }
462:
463: $this->flash($this->_config['authError']);
464: if ($this->_config['unauthorizedRedirect'] === true) {
465: $default = '/';
466: if (!empty($this->_config['loginRedirect'])) {
467: $default = $this->_config['loginRedirect'];
468: }
469: if (is_array($default)) {
470: $default['_base'] = false;
471: }
472: $url = $controller->referer($default, true);
473: } else {
474: $url = $this->_config['unauthorizedRedirect'];
475: }
476:
477: return $controller->redirect($url);
478: }
479:
480: /**
481: * Sets defaults for configs.
482: *
483: * @return void
484: */
485: protected function _setDefaults()
486: {
487: $defaults = [
488: 'authenticate' => ['Form'],
489: 'flash' => [
490: 'element' => 'error',
491: 'key' => 'flash',
492: 'params' => ['class' => 'error']
493: ],
494: 'loginAction' => [
495: 'controller' => 'Users',
496: 'action' => 'login',
497: 'plugin' => null
498: ],
499: 'logoutRedirect' => $this->_config['loginAction'],
500: 'authError' => __d('cake', 'You are not authorized to access that location.')
501: ];
502:
503: $config = $this->getConfig();
504: foreach ($config as $key => $value) {
505: if ($value !== null) {
506: unset($defaults[$key]);
507: }
508: }
509: $this->setConfig($defaults);
510: }
511:
512: /**
513: * Check if the provided user is authorized for the request.
514: *
515: * Uses the configured Authorization adapters to check whether or not a user is authorized.
516: * Each adapter will be checked in sequence, if any of them return true, then the user will
517: * be authorized for the request.
518: *
519: * @param array|\ArrayAccess|null $user The user to check the authorization of.
520: * If empty the user fetched from storage will be used.
521: * @param \Cake\Http\ServerRequest|null $request The request to authenticate for.
522: * If empty, the current request will be used.
523: * @return bool True if $user is authorized, otherwise false
524: */
525: public function isAuthorized($user = null, ServerRequest $request = null)
526: {
527: if (empty($user) && !$this->user()) {
528: return false;
529: }
530: if (empty($user)) {
531: $user = $this->user();
532: }
533: if (empty($request)) {
534: $request = $this->getController()->getRequest();
535: }
536: if (empty($this->_authorizeObjects)) {
537: $this->constructAuthorize();
538: }
539: foreach ($this->_authorizeObjects as $authorizer) {
540: if ($authorizer->authorize($user, $request) === true) {
541: $this->_authorizationProvider = $authorizer;
542:
543: return true;
544: }
545: }
546:
547: return false;
548: }
549:
550: /**
551: * Loads the authorization objects configured.
552: *
553: * @return array|null The loaded authorization objects, or null when authorize is empty.
554: * @throws \Cake\Core\Exception\Exception
555: */
556: public function constructAuthorize()
557: {
558: if (empty($this->_config['authorize'])) {
559: return null;
560: }
561: $this->_authorizeObjects = [];
562: $authorize = Hash::normalize((array)$this->_config['authorize']);
563: $global = [];
564: if (isset($authorize[AuthComponent::ALL])) {
565: $global = $authorize[AuthComponent::ALL];
566: unset($authorize[AuthComponent::ALL]);
567: }
568: foreach ($authorize as $alias => $config) {
569: if (!empty($config['className'])) {
570: $class = $config['className'];
571: unset($config['className']);
572: } else {
573: $class = $alias;
574: }
575: $className = App::className($class, 'Auth', 'Authorize');
576: if (!class_exists($className)) {
577: throw new Exception(sprintf('Authorization adapter "%s" was not found.', $class));
578: }
579: if (!method_exists($className, 'authorize')) {
580: throw new Exception('Authorization objects must implement an authorize() method.');
581: }
582: $config = (array)$config + $global;
583: $this->_authorizeObjects[$alias] = new $className($this->_registry, $config);
584: }
585:
586: return $this->_authorizeObjects;
587: }
588:
589: /**
590: * Getter for authorize objects. Will return a particular authorize object.
591: *
592: * @param string $alias Alias for the authorize object
593: * @return \Cake\Auth\BaseAuthorize|null
594: */
595: public function getAuthorize($alias)
596: {
597: if (empty($this->_authorizeObjects)) {
598: $this->constructAuthorize();
599: }
600:
601: return isset($this->_authorizeObjects[$alias]) ? $this->_authorizeObjects[$alias] : null;
602: }
603:
604: /**
605: * Takes a list of actions in the current controller for which authentication is not required, or
606: * no parameters to allow all actions.
607: *
608: * You can use allow with either an array or a simple string.
609: *
610: * ```
611: * $this->Auth->allow('view');
612: * $this->Auth->allow(['edit', 'add']);
613: * ```
614: * or to allow all actions
615: * ```
616: * $this->Auth->allow();
617: * ```
618: *
619: * @param string|array|null $actions Controller action name or array of actions
620: * @return void
621: * @link https://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-public
622: */
623: public function allow($actions = null)
624: {
625: if ($actions === null) {
626: $controller = $this->_registry->getController();
627: $this->allowedActions = get_class_methods($controller);
628:
629: return;
630: }
631: $this->allowedActions = array_merge($this->allowedActions, (array)$actions);
632: }
633:
634: /**
635: * Removes items from the list of allowed/no authentication required actions.
636: *
637: * You can use deny with either an array or a simple string.
638: *
639: * ```
640: * $this->Auth->deny('view');
641: * $this->Auth->deny(['edit', 'add']);
642: * ```
643: * or
644: * ```
645: * $this->Auth->deny();
646: * ```
647: * to remove all items from the allowed list
648: *
649: * @param string|array|null $actions Controller action name or array of actions
650: * @return void
651: * @see \Cake\Controller\Component\AuthComponent::allow()
652: * @link https://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-require-authorization
653: */
654: public function deny($actions = null)
655: {
656: if ($actions === null) {
657: $this->allowedActions = [];
658:
659: return;
660: }
661: foreach ((array)$actions as $action) {
662: $i = array_search($action, $this->allowedActions);
663: if (is_int($i)) {
664: unset($this->allowedActions[$i]);
665: }
666: }
667: $this->allowedActions = array_values($this->allowedActions);
668: }
669:
670: /**
671: * Set provided user info to storage as logged in user.
672: *
673: * The storage class is configured using `storage` config key or passing
674: * instance to AuthComponent::storage().
675: *
676: * @param array|\ArrayAccess $user User data.
677: * @return void
678: * @link https://book.cakephp.org/3.0/en/controllers/components/authentication.html#identifying-users-and-logging-them-in
679: */
680: public function setUser($user)
681: {
682: $this->storage()->write($user);
683: }
684:
685: /**
686: * Log a user out.
687: *
688: * Returns the logout action to redirect to. Triggers the `Auth.logout` event
689: * which the authenticate classes can listen for and perform custom logout logic.
690: *
691: * @return string Normalized config `logoutRedirect`
692: * @link https://book.cakephp.org/3.0/en/controllers/components/authentication.html#logging-users-out
693: */
694: public function logout()
695: {
696: $this->_setDefaults();
697: if (empty($this->_authenticateObjects)) {
698: $this->constructAuthenticate();
699: }
700: $user = (array)$this->user();
701: $this->dispatchEvent('Auth.logout', [$user]);
702: $this->storage()->delete();
703:
704: return Router::normalize($this->_config['logoutRedirect']);
705: }
706:
707: /**
708: * Get the current user from storage.
709: *
710: * @param string|null $key Field to retrieve. Leave null to get entire User record.
711: * @return mixed|null Either User record or null if no user is logged in, or retrieved field if key is specified.
712: * @link https://book.cakephp.org/3.0/en/controllers/components/authentication.html#accessing-the-logged-in-user
713: */
714: public function user($key = null)
715: {
716: $user = $this->storage()->read();
717: if (!$user) {
718: return null;
719: }
720:
721: if ($key === null) {
722: return $user;
723: }
724:
725: return Hash::get($user, $key);
726: }
727:
728: /**
729: * Similar to AuthComponent::user() except if user is not found in
730: * configured storage, connected authentication objects will have their
731: * getUser() methods called.
732: *
733: * This lets stateless authentication methods function correctly.
734: *
735: * @return bool true If a user can be found, false if one cannot.
736: */
737: protected function _getUser()
738: {
739: $user = $this->user();
740: if ($user) {
741: return true;
742: }
743:
744: if (empty($this->_authenticateObjects)) {
745: $this->constructAuthenticate();
746: }
747: foreach ($this->_authenticateObjects as $auth) {
748: $result = $auth->getUser($this->getController()->getRequest());
749: if (!empty($result) && is_array($result)) {
750: $this->_authenticationProvider = $auth;
751: $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
752: if ($event->getResult() !== null) {
753: $result = $event->getResult();
754: }
755: $this->storage()->write($result);
756:
757: return true;
758: }
759: }
760:
761: return false;
762: }
763:
764: /**
765: * Get the URL a user should be redirected to upon login.
766: *
767: * Pass a URL in to set the destination a user should be redirected to upon
768: * logging in.
769: *
770: * If no parameter is passed, gets the authentication redirect URL. The URL
771: * returned is as per following rules:
772: *
773: * - Returns the normalized redirect URL from storage if it is
774: * present and for the same domain the current app is running on.
775: * - If there is no URL returned from storage and there is a config
776: * `loginRedirect`, the `loginRedirect` value is returned.
777: * - If there is no session and no `loginRedirect`, / is returned.
778: *
779: * @param string|array|null $url Optional URL to write as the login redirect URL.
780: * @return string Redirect URL
781: */
782: public function redirectUrl($url = null)
783: {
784: $redirectUrl = $this->getController()->getRequest()->getQuery(static::QUERY_STRING_REDIRECT);
785: if ($redirectUrl && (substr($redirectUrl, 0, 1) !== '/' || substr($redirectUrl, 0, 2) === '//')) {
786: $redirectUrl = null;
787: }
788:
789: if ($url !== null) {
790: $redirectUrl = $url;
791: } elseif ($redirectUrl) {
792: if (Router::normalize($redirectUrl) === Router::normalize($this->_config['loginAction'])) {
793: $redirectUrl = $this->_config['loginRedirect'];
794: }
795: } elseif ($this->_config['loginRedirect']) {
796: $redirectUrl = $this->_config['loginRedirect'];
797: } else {
798: $redirectUrl = '/';
799: }
800: if (is_array($redirectUrl)) {
801: return Router::url($redirectUrl + ['_base' => false]);
802: }
803:
804: return $redirectUrl;
805: }
806:
807: /**
808: * Use the configured authentication adapters, and attempt to identify the user
809: * by credentials contained in $request.
810: *
811: * Triggers `Auth.afterIdentify` event which the authenticate classes can listen
812: * to.
813: *
814: * @return array|bool User record data, or false, if the user could not be identified.
815: */
816: public function identify()
817: {
818: $this->_setDefaults();
819:
820: if (empty($this->_authenticateObjects)) {
821: $this->constructAuthenticate();
822: }
823: foreach ($this->_authenticateObjects as $auth) {
824: $result = $auth->authenticate($this->getController()->getRequest(), $this->response);
825: if (!empty($result)) {
826: $this->_authenticationProvider = $auth;
827: $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]);
828: if ($event->getResult() !== null) {
829: return $event->getResult();
830: }
831:
832: return $result;
833: }
834: }
835:
836: return false;
837: }
838:
839: /**
840: * Loads the configured authentication objects.
841: *
842: * @return array|null The loaded authorization objects, or null on empty authenticate value.
843: * @throws \Cake\Core\Exception\Exception
844: */
845: public function constructAuthenticate()
846: {
847: if (empty($this->_config['authenticate'])) {
848: return null;
849: }
850: $this->_authenticateObjects = [];
851: $authenticate = Hash::normalize((array)$this->_config['authenticate']);
852: $global = [];
853: if (isset($authenticate[AuthComponent::ALL])) {
854: $global = $authenticate[AuthComponent::ALL];
855: unset($authenticate[AuthComponent::ALL]);
856: }
857: foreach ($authenticate as $alias => $config) {
858: if (!empty($config['className'])) {
859: $class = $config['className'];
860: unset($config['className']);
861: } else {
862: $class = $alias;
863: }
864: $className = App::className($class, 'Auth', 'Authenticate');
865: if (!class_exists($className)) {
866: throw new Exception(sprintf('Authentication adapter "%s" was not found.', $class));
867: }
868: if (!method_exists($className, 'authenticate')) {
869: throw new Exception('Authentication objects must implement an authenticate() method.');
870: }
871: $config = array_merge($global, (array)$config);
872: $this->_authenticateObjects[$alias] = new $className($this->_registry, $config);
873: $this->getEventManager()->on($this->_authenticateObjects[$alias]);
874: }
875:
876: return $this->_authenticateObjects;
877: }
878:
879: /**
880: * Get/set user record storage object.
881: *
882: * @param \Cake\Auth\Storage\StorageInterface|null $storage Sets provided
883: * object as storage or if null returns configured storage object.
884: * @return \Cake\Auth\Storage\StorageInterface|null
885: */
886: public function storage(StorageInterface $storage = null)
887: {
888: if ($storage !== null) {
889: $this->_storage = $storage;
890:
891: return null;
892: }
893:
894: if ($this->_storage) {
895: return $this->_storage;
896: }
897:
898: $config = $this->_config['storage'];
899: if (is_string($config)) {
900: $class = $config;
901: $config = [];
902: } else {
903: $class = $config['className'];
904: unset($config['className']);
905: }
906: $className = App::className($class, 'Auth/Storage', 'Storage');
907: if (!class_exists($className)) {
908: throw new Exception(sprintf('Auth storage adapter "%s" was not found.', $class));
909: }
910: $request = $this->getController()->getRequest();
911: $response = $this->getController()->getResponse();
912: $this->_storage = new $className($request, $response, $config);
913:
914: return $this->_storage;
915: }
916:
917: /**
918: * Magic accessor for backward compatibility for property `$sessionKey`.
919: *
920: * @param string $name Property name
921: * @return mixed
922: */
923: public function __get($name)
924: {
925: if ($name === 'sessionKey') {
926: return $this->storage()->getConfig('key');
927: }
928:
929: return parent::__get($name);
930: }
931:
932: /**
933: * Magic setter for backward compatibility for property `$sessionKey`.
934: *
935: * @param string $name Property name.
936: * @param mixed $value Value to set.
937: * @return void
938: */
939: public function __set($name, $value)
940: {
941: if ($name === 'sessionKey') {
942: $this->_storage = null;
943:
944: if ($value === false) {
945: $this->setConfig('storage', 'Memory');
946:
947: return;
948: }
949:
950: $this->setConfig('storage', 'Session');
951: $this->storage()->setConfig('key', $value);
952:
953: return;
954: }
955:
956: $this->{$name} = $value;
957: }
958:
959: /**
960: * Getter for authenticate objects. Will return a particular authenticate object.
961: *
962: * @param string $alias Alias for the authenticate object
963: *
964: * @return \Cake\Auth\BaseAuthenticate|null
965: */
966: public function getAuthenticate($alias)
967: {
968: if (empty($this->_authenticateObjects)) {
969: $this->constructAuthenticate();
970: }
971:
972: return isset($this->_authenticateObjects[$alias]) ? $this->_authenticateObjects[$alias] : null;
973: }
974:
975: /**
976: * Set a flash message. Uses the Flash component with values from `flash` config.
977: *
978: * @param string $message The message to set.
979: * @return void
980: */
981: public function flash($message)
982: {
983: if ($message === false) {
984: return;
985: }
986:
987: $this->Flash->set($message, $this->_config['flash']);
988: }
989:
990: /**
991: * If login was called during this request and the user was successfully
992: * authenticated, this function will return the instance of the authentication
993: * object that was used for logging the user in.
994: *
995: * @return \Cake\Auth\BaseAuthenticate|null
996: */
997: public function authenticationProvider()
998: {
999: return $this->_authenticationProvider;
1000: }
1001:
1002: /**
1003: * If there was any authorization processing for the current request, this function
1004: * will return the instance of the Authorization object that granted access to the
1005: * user to the current address.
1006: *
1007: * @return \Cake\Auth\BaseAuthorize|null
1008: */
1009: public function authorizationProvider()
1010: {
1011: return $this->_authorizationProvider;
1012: }
1013:
1014: /**
1015: * Returns the URL to redirect back to or / if not possible.
1016: *
1017: * This method takes the referrer into account if the
1018: * request is not of type GET.
1019: *
1020: * @return string
1021: */
1022: protected function _getUrlToRedirectBackTo()
1023: {
1024: $urlToRedirectBackTo = $this->request->getRequestTarget();
1025: if (!$this->request->is('get')) {
1026: $urlToRedirectBackTo = $this->request->referer(true);
1027: }
1028:
1029: return $urlToRedirectBackTo;
1030: }
1031: }
1032: