AuthComponent.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 0.10.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Controller\Component;
  16. use Cake\Controller\Component;
  17. use Cake\Controller\Controller;
  18. use Cake\Core\App;
  19. use Cake\Core\Exception\Exception;
  20. use Cake\Event\Event;
  21. use Cake\Event\EventManagerTrait;
  22. use Cake\Network\Exception\ForbiddenException;
  23. use Cake\Network\Request;
  24. use Cake\Network\Response;
  25. use Cake\Routing\Router;
  26. use Cake\Utility\Hash;
  27. /**
  28. * Authentication control component class
  29. *
  30. * Binds access control with user authentication and session management.
  31. *
  32. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html
  33. */
  34. class AuthComponent extends Component
  35. {
  36. use EventManagerTrait;
  37. /**
  38. * Constant for 'all'
  39. *
  40. * @var string
  41. */
  42. const ALL = 'all';
  43. /**
  44. * Default config
  45. *
  46. * - `authenticate` - An array of authentication objects to use for authenticating users.
  47. * You can configure multiple adapters and they will be checked sequentially
  48. * when users are identified.
  49. *
  50. * ```
  51. * $this->Auth->config('authenticate', [
  52. * 'Form' => [
  53. * 'userModel' => 'Users.Users'
  54. * ]
  55. * ]);
  56. * ```
  57. *
  58. * Using the class name without 'Authenticate' as the key, you can pass in an
  59. * array of config for each authentication object. Additionally you can define
  60. * config that should be set to all authentications objects using the 'all' key:
  61. *
  62. * ```
  63. * $this->Auth->config('authenticate', [
  64. * AuthComponent::ALL => [
  65. * 'userModel' => 'Users.Users',
  66. * 'scope' => ['Users.active' => 1]
  67. * ],
  68. * 'Form',
  69. * 'Basic'
  70. * ]);
  71. * ```
  72. *
  73. * - `authorize` - An array of authorization objects to use for authorizing users.
  74. * You can configure multiple adapters and they will be checked sequentially
  75. * when authorization checks are done.
  76. *
  77. * ```
  78. * $this->Auth->config('authorize', [
  79. * 'Crud' => [
  80. * 'actionPath' => 'controllers/'
  81. * ]
  82. * ]);
  83. * ```
  84. *
  85. * Using the class name without 'Authorize' as the key, you can pass in an array
  86. * of config for each authorization object. Additionally you can define config
  87. * that should be set to all authorization objects using the AuthComponent::ALL key:
  88. *
  89. * ```
  90. * $this->Auth->config('authorize', [
  91. * AuthComponent::ALL => [
  92. * 'actionPath' => 'controllers/'
  93. * ],
  94. * 'Crud',
  95. * 'CustomAuth'
  96. * ]);
  97. * ```
  98. *
  99. * - `ajaxLogin` - The name of an optional view element to render when an Ajax
  100. * request is made with an invalid or expired session.
  101. *
  102. * - `flash` - Settings to use when Auth needs to do a flash message with
  103. * FlashComponent::set(). Available keys are:
  104. *
  105. * - `key` - The message domain to use for flashes generated by this component,
  106. * defaults to 'auth'.
  107. * - `element` - Flash element to use, defaults to 'default'.
  108. * - `params` - The array of additional params to use, defaults to ['class' => 'error']
  109. *
  110. * - `loginAction` - A URL (defined as a string or array) to the controller action
  111. * that handles logins. Defaults to `/users/login`.
  112. *
  113. * - `loginRedirect` - Normally, if a user is redirected to the `loginAction` page,
  114. * the location they were redirected from will be stored in the session so that
  115. * they can be redirected back after a successful login. If this session value
  116. * is not set, redirectUrl() method will return the URL specified in `loginRedirect`.
  117. *
  118. * - `logoutRedirect` - The default action to redirect to after the user is logged out.
  119. * While AuthComponent does not handle post-logout redirection, a redirect URL
  120. * will be returned from `AuthComponent::logout()`. Defaults to `loginAction`.
  121. *
  122. * - `authError` - Error to display when user attempts to access an object or
  123. * action to which they do not have access.
  124. *
  125. * - `unauthorizedRedirect` - Controls handling of unauthorized access.
  126. *
  127. * - For default value `true` unauthorized user is redirected to the referrer URL
  128. * or `$loginRedirect` or '/'.
  129. * - If set to a string or array the value is used as a URL to redirect to.
  130. * - If set to false a `ForbiddenException` exception is thrown instead of redirecting.
  131. *
  132. * @var array
  133. */
  134. protected $_defaultConfig = [
  135. 'authenticate' => null,
  136. 'authorize' => null,
  137. 'ajaxLogin' => null,
  138. 'flash' => null,
  139. 'loginAction' => null,
  140. 'loginRedirect' => null,
  141. 'logoutRedirect' => null,
  142. 'authError' => null,
  143. 'unauthorizedRedirect' => true
  144. ];
  145. /**
  146. * Other components utilized by AuthComponent
  147. *
  148. * @var array
  149. */
  150. public $components = ['RequestHandler', 'Flash'];
  151. /**
  152. * Objects that will be used for authentication checks.
  153. *
  154. * @var array
  155. */
  156. protected $_authenticateObjects = [];
  157. /**
  158. * Objects that will be used for authorization checks.
  159. *
  160. * @var array
  161. */
  162. protected $_authorizeObjects = [];
  163. /**
  164. * The session key name where the record of the current user is stored. Default
  165. * key is "Auth.User". If you are using only stateless authenticators set this
  166. * to false to ensure session is not started.
  167. *
  168. * @var string
  169. */
  170. public $sessionKey = 'Auth.User';
  171. /**
  172. * The current user, used for stateless authentication when
  173. * sessions are not available.
  174. *
  175. * @var array
  176. */
  177. protected $_user = [];
  178. /**
  179. * Controller actions for which user validation is not required.
  180. *
  181. * @var array
  182. * @see AuthComponent::allow()
  183. */
  184. public $allowedActions = [];
  185. /**
  186. * Request object
  187. *
  188. * @var \Cake\Network\Request
  189. */
  190. public $request;
  191. /**
  192. * Response object
  193. *
  194. * @var \Cake\Network\Response
  195. */
  196. public $response;
  197. /**
  198. * Instance of the Session object
  199. *
  200. * @var \Cake\Network\Session
  201. */
  202. public $session;
  203. /**
  204. * The instance of the Authenticate provider that was used for
  205. * successfully logging in the current user after calling `login()`
  206. * in the same request
  207. *
  208. * @var \Cake\Auth\BaseAuthenticate
  209. */
  210. protected $_authenticationProvider;
  211. /**
  212. * The instance of the Authorize provider that was used to grant
  213. * access to the current user to the url they are requesting.
  214. *
  215. * @var \Cake\Auth\BaseAuthorize
  216. */
  217. protected $_authorizationProvider;
  218. /**
  219. * Initialize properties.
  220. *
  221. * @param array $config The config data.
  222. * @return void
  223. */
  224. public function initialize(array $config)
  225. {
  226. $controller = $this->_registry->getController();
  227. $this->eventManager($controller->eventManager());
  228. $this->response =& $controller->response;
  229. $this->session = $controller->request->session();
  230. }
  231. /**
  232. * Main execution method. Handles redirecting of invalid users, and processing
  233. * of login form data.
  234. *
  235. * @param \Cake\Event\Event $event The startup event.
  236. * @return void|\Cake\Network\Response
  237. */
  238. public function startup(Event $event)
  239. {
  240. $controller = $event->subject();
  241. $action = strtolower($controller->request->params['action']);
  242. if (!$controller->isAction($action)) {
  243. return;
  244. }
  245. $this->_setDefaults();
  246. if ($this->_isAllowed($controller)) {
  247. return;
  248. }
  249. if (!$this->_getUser()) {
  250. $result = $this->_unauthenticated($controller);
  251. if ($result instanceof Response) {
  252. $event->stopPropagation();
  253. }
  254. return $result;
  255. }
  256. if ($this->_isLoginAction($controller) ||
  257. empty($this->_config['authorize']) ||
  258. $this->isAuthorized($this->user())
  259. ) {
  260. return;
  261. }
  262. $event->stopPropagation();
  263. return $this->_unauthorized($controller);
  264. }
  265. /**
  266. * Events supported by this component.
  267. *
  268. * @return array
  269. */
  270. public function implementedEvents()
  271. {
  272. return [
  273. 'Controller.startup' => 'startup',
  274. ];
  275. }
  276. /**
  277. * Checks whether current action is accessible without authentication.
  278. *
  279. * @param \Cake\Controller\Controller $controller A reference to the instantiating
  280. * controller object
  281. * @return bool True if action is accessible without authentication else false
  282. */
  283. protected function _isAllowed(Controller $controller)
  284. {
  285. $action = strtolower($controller->request->params['action']);
  286. if (in_array($action, array_map('strtolower', $this->allowedActions))) {
  287. return true;
  288. }
  289. return false;
  290. }
  291. /**
  292. * Handles unauthenticated access attempt. First the `unauthenticated()` method
  293. * of the last authenticator in the chain will be called. The authenticator can
  294. * handle sending response or redirection as appropriate and return `true` to
  295. * indicate no further action is necessary. If authenticator returns null this
  296. * method redirects user to login action. If it's an AJAX request and config
  297. * `ajaxLogin` is specified that element is rendered else a 403 HTTP status code
  298. * is returned.
  299. *
  300. * @param \Cake\Controller\Controller $controller A reference to the controller object.
  301. * @return void|\Cake\Network\Response Null if current action is login action
  302. * else response object returned by authenticate object or Controller::redirect().
  303. */
  304. protected function _unauthenticated(Controller $controller)
  305. {
  306. if (empty($this->_authenticateObjects)) {
  307. $this->constructAuthenticate();
  308. }
  309. $auth = end($this->_authenticateObjects);
  310. $result = $auth->unauthenticated($this->request, $this->response);
  311. if ($result !== null) {
  312. return $result;
  313. }
  314. if ($this->_isLoginAction($controller)) {
  315. if (empty($controller->request->data) &&
  316. !$this->session->check('Auth.redirect') &&
  317. $this->request->env('HTTP_REFERER')
  318. ) {
  319. $this->session->write('Auth.redirect', $controller->referer(null, true));
  320. }
  321. return;
  322. }
  323. if (!$controller->request->is('ajax')) {
  324. $this->flash($this->_config['authError']);
  325. $this->session->write('Auth.redirect', $controller->request->here(false));
  326. return $controller->redirect($this->_config['loginAction']);
  327. }
  328. if (!empty($this->_config['ajaxLogin'])) {
  329. $controller->viewPath = 'Element';
  330. $response = $controller->render(
  331. $this->_config['ajaxLogin'],
  332. $this->RequestHandler->ajaxLayout
  333. );
  334. $response->statusCode(403);
  335. return $response;
  336. }
  337. $this->response->statusCode(403);
  338. return $this->response;
  339. }
  340. /**
  341. * Normalizes config `loginAction` and checks if current request URL is same as login action.
  342. *
  343. * @param \Cake\Controller\Controller $controller A reference to the controller object.
  344. * @return bool True if current action is login action else false.
  345. */
  346. protected function _isLoginAction(Controller $controller)
  347. {
  348. $url = '';
  349. if (isset($controller->request->url)) {
  350. $url = $controller->request->url;
  351. }
  352. $url = Router::normalize($url);
  353. $loginAction = Router::normalize($this->_config['loginAction']);
  354. return $loginAction === $url;
  355. }
  356. /**
  357. * Handle unauthorized access attempt
  358. *
  359. * @param \Cake\Controller\Controller $controller A reference to the controller object
  360. * @return \Cake\Network\Response
  361. * @throws \Cake\Network\Exception\ForbiddenException
  362. */
  363. protected function _unauthorized(Controller $controller)
  364. {
  365. if ($this->_config['unauthorizedRedirect'] === false) {
  366. throw new ForbiddenException($this->_config['authError']);
  367. }
  368. $this->flash($this->_config['authError']);
  369. if ($this->_config['unauthorizedRedirect'] === true) {
  370. $default = '/';
  371. if (!empty($this->_config['loginRedirect'])) {
  372. $default = $this->_config['loginRedirect'];
  373. }
  374. $url = $controller->referer($default, true);
  375. } else {
  376. $url = $this->_config['unauthorizedRedirect'];
  377. }
  378. return $controller->redirect($url);
  379. }
  380. /**
  381. * Sets defaults for configs.
  382. *
  383. * @return void
  384. */
  385. protected function _setDefaults()
  386. {
  387. $defaults = [
  388. 'authenticate' => ['Form'],
  389. 'flash' => [
  390. 'element' => 'default',
  391. 'key' => 'auth',
  392. 'params' => ['class' => 'error']
  393. ],
  394. 'loginAction' => [
  395. 'controller' => 'Users',
  396. 'action' => 'login',
  397. 'plugin' => null
  398. ],
  399. 'logoutRedirect' => $this->_config['loginAction'],
  400. 'authError' => __d('cake', 'You are not authorized to access that location.')
  401. ];
  402. $config = $this->config();
  403. foreach ($config as $key => $value) {
  404. if ($value !== null) {
  405. unset($defaults[$key]);
  406. }
  407. }
  408. $this->config($defaults);
  409. }
  410. /**
  411. * Check if the provided user is authorized for the request.
  412. *
  413. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  414. * Each adapter will be checked in sequence, if any of them return true, then the user will
  415. * be authorized for the request.
  416. *
  417. * @param array|null $user The user to check the authorization of. If empty the user in the session will be used.
  418. * @param \Cake\Network\Request|null $request The request to authenticate for. If empty, the current request will be used.
  419. * @return bool True if $user is authorized, otherwise false
  420. */
  421. public function isAuthorized($user = null, Request $request = null)
  422. {
  423. if (empty($user) && !$this->user()) {
  424. return false;
  425. }
  426. if (empty($user)) {
  427. $user = $this->user();
  428. }
  429. if (empty($request)) {
  430. $request = $this->request;
  431. }
  432. if (empty($this->_authorizeObjects)) {
  433. $this->constructAuthorize();
  434. }
  435. foreach ($this->_authorizeObjects as $authorizer) {
  436. if ($authorizer->authorize($user, $request) === true) {
  437. $this->_authorizationProvider = $authorizer;
  438. return true;
  439. }
  440. }
  441. return false;
  442. }
  443. /**
  444. * Loads the authorization objects configured.
  445. *
  446. * @return mixed Either null when authorize is empty, or the loaded authorization objects.
  447. * @throws \Cake\Core\Exception\Exception
  448. */
  449. public function constructAuthorize()
  450. {
  451. if (empty($this->_config['authorize'])) {
  452. return;
  453. }
  454. $this->_authorizeObjects = [];
  455. $authorize = Hash::normalize((array)$this->_config['authorize']);
  456. $global = [];
  457. if (isset($authorize[AuthComponent::ALL])) {
  458. $global = $authorize[AuthComponent::ALL];
  459. unset($authorize[AuthComponent::ALL]);
  460. }
  461. foreach ($authorize as $alias => $config) {
  462. if (!empty($config['className'])) {
  463. $class = $config['className'];
  464. unset($config['className']);
  465. } else {
  466. $class = $alias;
  467. }
  468. $className = App::className($class, 'Auth', 'Authorize');
  469. if (!class_exists($className)) {
  470. throw new Exception(sprintf('Authorization adapter "%s" was not found.', $class));
  471. }
  472. if (!method_exists($className, 'authorize')) {
  473. throw new Exception('Authorization objects must implement an authorize() method.');
  474. }
  475. $config = (array)$config + $global;
  476. $this->_authorizeObjects[$alias] = new $className($this->_registry, $config);
  477. }
  478. return $this->_authorizeObjects;
  479. }
  480. /**
  481. * Getter for authorize objects. Will return a particular authorize object.
  482. *
  483. * @param string $alias Alias for the authorize object
  484. * @return \Cake\Auth\BaseAuthorize|null
  485. */
  486. public function getAuthorize($alias)
  487. {
  488. if (empty($this->_authorizeObjects)) {
  489. $this->constructAuthorize();
  490. }
  491. return isset($this->_authorizeObjects[$alias]) ? $this->_authorizeObjects[$alias] : null;
  492. }
  493. /**
  494. * Takes a list of actions in the current controller for which authentication is not required, or
  495. * no parameters to allow all actions.
  496. *
  497. * You can use allow with either an array or a simple string.
  498. *
  499. * ```
  500. * $this->Auth->allow('view');
  501. * $this->Auth->allow(['edit', 'add']);
  502. * ```
  503. * or to allow all actions
  504. * ```
  505. * $this->Auth->allow();
  506. * ```
  507. *
  508. * @param string|array $actions Controller action name or array of actions
  509. * @return void
  510. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-public
  511. */
  512. public function allow($actions = null)
  513. {
  514. if ($actions === null) {
  515. $controller = $this->_registry->getController();
  516. $this->allowedActions = get_class_methods($controller);
  517. return;
  518. }
  519. $this->allowedActions = array_merge($this->allowedActions, (array)$actions);
  520. }
  521. /**
  522. * Removes items from the list of allowed/no authentication required actions.
  523. *
  524. * You can use deny with either an array or a simple string.
  525. *
  526. * ```
  527. * $this->Auth->deny('view');
  528. * $this->Auth->deny(['edit', 'add']);
  529. * ```
  530. * or
  531. * ```
  532. * $this->Auth->deny();
  533. * ```
  534. * to remove all items from the allowed list
  535. *
  536. * @param string|array $actions Controller action name or array of actions
  537. * @return void
  538. * @see AuthComponent::allow()
  539. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#making-actions-require-authorization
  540. */
  541. public function deny($actions = null)
  542. {
  543. if ($actions === null) {
  544. $this->allowedActions = [];
  545. return;
  546. }
  547. foreach ((array)$actions as $action) {
  548. $i = array_search($action, $this->allowedActions);
  549. if (is_int($i)) {
  550. unset($this->allowedActions[$i]);
  551. }
  552. }
  553. $this->allowedActions = array_values($this->allowedActions);
  554. }
  555. /**
  556. * Set provided user info to session as logged in user.
  557. *
  558. * The user record is written to the session key specified in AuthComponent::$sessionKey.
  559. * The session id will also be changed in order to help mitigate session replays.
  560. *
  561. * @param array $user Array of user data.
  562. * @return void
  563. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#identifying-users-and-logging-them-in
  564. */
  565. public function setUser(array $user)
  566. {
  567. $this->session->renew();
  568. $this->session->write($this->sessionKey, $user);
  569. }
  570. /**
  571. * Log a user out.
  572. *
  573. * Returns the logout action to redirect to. Triggers the `Auth.logout` event
  574. * which the authenticate classes can listen for and perform custom logout logic.
  575. * AuthComponent will remove the session data, so there is no need to do that
  576. * in an authentication object. Logging out will also renew the session id.
  577. * This helps mitigate issues with session replays.
  578. *
  579. * @return string Normalized config `logoutRedirect`
  580. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#logging-users-out
  581. */
  582. public function logout()
  583. {
  584. $this->_setDefaults();
  585. if (empty($this->_authenticateObjects)) {
  586. $this->constructAuthenticate();
  587. }
  588. $user = (array)$this->user();
  589. $this->dispatchEvent('Auth.logout', [$user]);
  590. $this->session->delete($this->sessionKey);
  591. $this->session->delete('Auth.redirect');
  592. $this->session->renew();
  593. return Router::normalize($this->_config['logoutRedirect']);
  594. }
  595. /**
  596. * Get the current user.
  597. *
  598. * Will prefer the user cache over sessions. The user cache is primarily used for
  599. * stateless authentication. For stateful authentication,
  600. * cookies + sessions will be used.
  601. *
  602. * @param string $key field to retrieve. Leave null to get entire User record
  603. * @return array|null Either User record or null if no user is logged in.
  604. * @link http://book.cakephp.org/3.0/en/controllers/components/authentication.html#accessing-the-logged-in-user
  605. */
  606. public function user($key = null)
  607. {
  608. if (!empty($this->_user)) {
  609. $user = $this->_user;
  610. } elseif ($this->sessionKey && $this->session->check($this->sessionKey)) {
  611. $user = $this->session->read($this->sessionKey);
  612. } else {
  613. return null;
  614. }
  615. if ($key === null) {
  616. return $user;
  617. }
  618. return Hash::get($user, $key);
  619. }
  620. /**
  621. * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
  622. * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
  623. *
  624. * @return bool true if a user can be found, false if one cannot.
  625. */
  626. protected function _getUser()
  627. {
  628. $user = $this->user();
  629. if ($user) {
  630. $this->session->delete('Auth.redirect');
  631. return true;
  632. }
  633. if (empty($this->_authenticateObjects)) {
  634. $this->constructAuthenticate();
  635. }
  636. foreach ($this->_authenticateObjects as $auth) {
  637. $result = $auth->getUser($this->request);
  638. if (!empty($result) && is_array($result)) {
  639. $this->_user = $result;
  640. return true;
  641. }
  642. }
  643. return false;
  644. }
  645. /**
  646. * Get the URL a user should be redirected to upon login.
  647. *
  648. * Pass a URL in to set the destination a user should be redirected to upon
  649. * logging in.
  650. *
  651. * If no parameter is passed, gets the authentication redirect URL. The URL
  652. * returned is as per following rules:
  653. *
  654. * - Returns the normalized URL from session Auth.redirect value if it is
  655. * present and for the same domain the current app is running on.
  656. * - If there is no session value and there is a config `loginRedirect`, the
  657. * `loginRedirect` value is returned.
  658. * - If there is no session and no `loginRedirect`, / is returned.
  659. *
  660. * @param string|array $url Optional URL to write as the login redirect URL.
  661. * @return string Redirect URL
  662. */
  663. public function redirectUrl($url = null)
  664. {
  665. if ($url !== null) {
  666. $redir = $url;
  667. $this->session->write('Auth.redirect', $redir);
  668. } elseif ($this->session->check('Auth.redirect')) {
  669. $redir = $this->session->read('Auth.redirect');
  670. $this->session->delete('Auth.redirect');
  671. if (Router::normalize($redir) === Router::normalize($this->_config['loginAction'])) {
  672. $redir = $this->_config['loginRedirect'];
  673. }
  674. } elseif ($this->_config['loginRedirect']) {
  675. $redir = $this->_config['loginRedirect'];
  676. } else {
  677. $redir = '/';
  678. }
  679. if (is_array($redir)) {
  680. return Router::url($redir + ['_base' => false]);
  681. }
  682. return $redir;
  683. }
  684. /**
  685. * Use the configured authentication adapters, and attempt to identify the user
  686. * by credentials contained in $request.
  687. *
  688. * Triggers `Auth.afterIdentify` event which the authenticate classes can listen
  689. * to.
  690. *
  691. * @return array User record data, or false, if the user could not be identified.
  692. */
  693. public function identify()
  694. {
  695. $this->_setDefaults();
  696. if (empty($this->_authenticateObjects)) {
  697. $this->constructAuthenticate();
  698. }
  699. foreach ($this->_authenticateObjects as $auth) {
  700. $result = $auth->authenticate($this->request, $this->response);
  701. if (!empty($result) && is_array($result)) {
  702. $this->_authenticationProvider = $auth;
  703. $this->dispatchEvent('Auth.afterIdentify', [$result]);
  704. return $result;
  705. }
  706. }
  707. return false;
  708. }
  709. /**
  710. * Loads the configured authentication objects.
  711. *
  712. * @return mixed either null on empty authenticate value, or an array of loaded objects.
  713. * @throws \Cake\Core\Exception\Exception
  714. */
  715. public function constructAuthenticate()
  716. {
  717. if (empty($this->_config['authenticate'])) {
  718. return;
  719. }
  720. $this->_authenticateObjects = [];
  721. $authenticate = Hash::normalize((array)$this->_config['authenticate']);
  722. $global = [];
  723. if (isset($authenticate[AuthComponent::ALL])) {
  724. $global = $authenticate[AuthComponent::ALL];
  725. unset($authenticate[AuthComponent::ALL]);
  726. }
  727. foreach ($authenticate as $alias => $config) {
  728. if (!empty($config['className'])) {
  729. $class = $config['className'];
  730. unset($config['className']);
  731. } else {
  732. $class = $alias;
  733. }
  734. $className = App::className($class, 'Auth', 'Authenticate');
  735. if (!class_exists($className)) {
  736. throw new Exception(sprintf('Authentication adapter "%s" was not found.', $class));
  737. }
  738. if (!method_exists($className, 'authenticate')) {
  739. throw new Exception('Authentication objects must implement an authenticate() method.');
  740. }
  741. $config = array_merge($global, (array)$config);
  742. $this->_authenticateObjects[$alias] = new $className($this->_registry, $config);
  743. $this->eventManager()->on($this->_authenticateObjects[$alias]);
  744. }
  745. return $this->_authenticateObjects;
  746. }
  747. /**
  748. * Getter for authenticate objects. Will return a particular authenticate object.
  749. *
  750. * @param string $alias Alias for the authenticate object
  751. *
  752. * @return \Cake\Auth\BaseAuthenticate|null
  753. */
  754. public function getAuthenticate($alias)
  755. {
  756. if (empty($this->_authenticateObjects)) {
  757. $this->constructAuthenticate();
  758. }
  759. return isset($this->_authenticateObjects[$alias]) ? $this->_authenticateObjects[$alias] : null;
  760. }
  761. /**
  762. * Set a flash message. Uses the Flash component with values from `flash` config.
  763. *
  764. * @param string $message The message to set.
  765. * @return void
  766. */
  767. public function flash($message)
  768. {
  769. if ($message !== false) {
  770. $this->Flash->set($message, $this->_config['flash']);
  771. }
  772. }
  773. /**
  774. * If login was called during this request and the user was successfully
  775. * authenticated, this function will return the instance of the authentication
  776. * object that was used for logging the user in.
  777. *
  778. * @return \Cake\Auth\BaseAuthenticate|null
  779. */
  780. public function authenticationProvider()
  781. {
  782. return $this->_authenticationProvider;
  783. }
  784. /**
  785. * If there was any authorization processing for the current request, this function
  786. * will return the instance of the Authorization object that granted access to the
  787. * user to the current address.
  788. *
  789. * @return \Cake\Auth\BaseAuthorize|null
  790. */
  791. public function authorizationProvider()
  792. {
  793. return $this->_authorizationProvider;
  794. }
  795. }