AuthComponent.php 23 KB

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