AuthComponent.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. * SessionComponent::setFlash(). Available keys are:
  105. *
  106. * - `element` - The element to use, defaults to 'default'.
  107. * - `key` - The key to use, defaults to 'auth'
  108. * - `params` - The array of additional params to use, defaults to []
  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 = array('Session', 'RequestHandler');
  151. /**
  152. * Objects that will be used for authentication checks.
  153. *
  154. * @var array
  155. */
  156. protected $_authenticateObjects = array();
  157. /**
  158. * Objects that will be used for authorization checks.
  159. *
  160. * @var array
  161. */
  162. protected $_authorizeObjects = array();
  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 static $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 static $_user = array();
  178. /**
  179. * Controller actions for which user validation is not required.
  180. *
  181. * @var array
  182. * @see AuthComponent::allow()
  183. */
  184. public $allowedActions = array();
  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. * Method list for bound controller.
  199. *
  200. * @var array
  201. */
  202. protected $_methods = array();
  203. /**
  204. * Initializes AuthComponent for use in the controller.
  205. *
  206. * @param Event $event The initialize event.
  207. * @return void
  208. */
  209. public function initialize(Event $event) {
  210. $controller = $event->subject();
  211. $this->request = $controller->request;
  212. $this->response = $controller->response;
  213. $this->_methods = $controller->methods;
  214. if (Configure::read('debug')) {
  215. Debugger::checkSecurityKeys();
  216. }
  217. }
  218. /**
  219. * Main execution method. Handles redirecting of invalid users, and processing
  220. * of login form data.
  221. *
  222. * @param Event $event The startup event.
  223. * @return void|\Cake\Network\Response
  224. */
  225. public function startup(Event $event) {
  226. $controller = $event->subject();
  227. $methods = array_flip(array_map('strtolower', $controller->methods));
  228. $action = strtolower($controller->request->params['action']);
  229. if (!isset($methods[$action])) {
  230. return;
  231. }
  232. $this->_setDefaults();
  233. if ($this->_isAllowed($controller)) {
  234. return;
  235. }
  236. if (!$this->_getUser()) {
  237. $result = $this->_unauthenticated($controller);
  238. if ($result instanceof Response) {
  239. $event->stopPropagation();
  240. }
  241. return $result;
  242. }
  243. if ($this->_isLoginAction($controller) ||
  244. empty($this->_config['authorize']) ||
  245. $this->isAuthorized($this->user())
  246. ) {
  247. return;
  248. }
  249. $event->stopPropagation();
  250. return $this->_unauthorized($controller);
  251. }
  252. /**
  253. * Checks whether current action is accessible without authentication.
  254. *
  255. * @param Controller $controller A reference to the instantiating controller object
  256. * @return bool True if action is accessible without authentication else false
  257. */
  258. protected function _isAllowed(Controller $controller) {
  259. $action = strtolower($controller->request->params['action']);
  260. if (in_array($action, array_map('strtolower', $this->allowedActions))) {
  261. return true;
  262. }
  263. return false;
  264. }
  265. /**
  266. * Handles unauthenticated access attempt. First the `unathenticated()` method
  267. * of the last authenticator in the chain will be called. The authenticator can
  268. * handle sending response or redirection as appropriate and return `true` to
  269. * indicate no furthur action is necessary. If authenticator returns null this
  270. * method redirects user to login action. If it's an ajax request and config
  271. * `ajaxLogin` is specified that element is rendered else a 403 http status code
  272. * is returned.
  273. *
  274. * @param Controller $controller A reference to the controller object.
  275. * @return void|\Cake\Network\Response Null if current action is login action
  276. * else response object returned by authenticate object or Controller::redirect().
  277. */
  278. protected function _unauthenticated(Controller $controller) {
  279. if (empty($this->_authenticateObjects)) {
  280. $this->constructAuthenticate();
  281. }
  282. $auth = $this->_authenticateObjects[count($this->_authenticateObjects) - 1];
  283. $result = $auth->unauthenticated($this->request, $this->response);
  284. if ($result !== null) {
  285. return $result;
  286. }
  287. if ($this->_isLoginAction($controller)) {
  288. if (empty($controller->request->data) &&
  289. !$this->Session->check('Auth.redirect') &&
  290. $this->request->env('HTTP_REFERER')
  291. ) {
  292. $this->Session->write('Auth.redirect', $controller->referer(null, true));
  293. }
  294. return;
  295. }
  296. if (!$controller->request->is('ajax')) {
  297. $this->flash($this->_config['authError']);
  298. $this->Session->write('Auth.redirect', $controller->request->here(false));
  299. return $controller->redirect($this->_config['loginAction']);
  300. }
  301. if (!empty($this->_config['ajaxLogin'])) {
  302. $controller->viewPath = 'Element';
  303. $response = $controller->render(
  304. $this->_config['ajaxLogin'],
  305. $this->RequestHandler->ajaxLayout
  306. );
  307. $response->statusCode(403);
  308. return $response;
  309. }
  310. return $controller->redirect(null, 403);
  311. }
  312. /**
  313. * Normalizes config `loginAction` and checks if current request URL is same as login action.
  314. *
  315. * @param Controller $controller A reference to the controller object.
  316. * @return bool True if current action is login action else false.
  317. */
  318. protected function _isLoginAction(Controller $controller) {
  319. $url = '';
  320. if (isset($controller->request->url)) {
  321. $url = $controller->request->url;
  322. }
  323. $url = Router::normalize($url);
  324. $loginAction = Router::normalize($this->_config['loginAction']);
  325. return $loginAction === $url;
  326. }
  327. /**
  328. * Handle unauthorized access attempt
  329. *
  330. * @param Controller $controller A reference to the controller object
  331. * @return \Cake\Network\Response
  332. * @throws \Cake\Error\ForbiddenException
  333. */
  334. protected function _unauthorized(Controller $controller) {
  335. if ($this->_config['unauthorizedRedirect'] === false) {
  336. throw new Error\ForbiddenException($this->_config['authError']);
  337. }
  338. $this->flash($this->_config['authError']);
  339. if ($this->_config['unauthorizedRedirect'] === true) {
  340. $default = '/';
  341. if (!empty($this->_config['loginRedirect'])) {
  342. $default = $this->_config['loginRedirect'];
  343. }
  344. $url = $controller->referer($default, true);
  345. } else {
  346. $url = $this->_config['unauthorizedRedirect'];
  347. }
  348. return $controller->redirect($url);
  349. }
  350. /**
  351. * Sets defaults for configs.
  352. *
  353. * @return void
  354. */
  355. protected function _setDefaults() {
  356. $defaults = [
  357. 'authenticate' => ['Form'],
  358. 'flash' => [
  359. 'element' => 'default',
  360. 'key' => 'auth',
  361. 'params' => []
  362. ],
  363. 'loginAction' => [
  364. 'controller' => 'users',
  365. 'action' => 'login',
  366. 'plugin' => null
  367. ],
  368. 'logoutRedirect' => $this->_config['loginAction'],
  369. 'authError' => __d('cake', 'You are not authorized to access that location.')
  370. ];
  371. $config = $this->config();
  372. foreach ($config as $key => $value) {
  373. if ($value !== null) {
  374. unset($defaults[$key]);
  375. }
  376. }
  377. $this->config($defaults);
  378. }
  379. /**
  380. * Check if the provided user is authorized for the request.
  381. *
  382. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  383. * Each adapter will be checked in sequence, if any of them return true, then the user will
  384. * be authorized for the request.
  385. *
  386. * @param array $user The user to check the authorization of. If empty the user in the session will be used.
  387. * @param \Cake\Network\Request $request The request to authenticate for. If empty, the current request will be used.
  388. * @return bool True if $user is authorized, otherwise false
  389. */
  390. public function isAuthorized($user = null, Request $request = null) {
  391. if (empty($user) && !$this->user()) {
  392. return false;
  393. }
  394. if (empty($user)) {
  395. $user = $this->user();
  396. }
  397. if (empty($request)) {
  398. $request = $this->request;
  399. }
  400. if (empty($this->_authorizeObjects)) {
  401. $this->constructAuthorize();
  402. }
  403. foreach ($this->_authorizeObjects as $authorizer) {
  404. if ($authorizer->authorize($user, $request) === true) {
  405. return true;
  406. }
  407. }
  408. return false;
  409. }
  410. /**
  411. * Loads the authorization objects configured.
  412. *
  413. * @return mixed Either null when authorize is empty, or the loaded authorization objects.
  414. * @throws \Cake\Error\Exception
  415. */
  416. public function constructAuthorize() {
  417. if (empty($this->_config['authorize'])) {
  418. return;
  419. }
  420. $this->_authorizeObjects = array();
  421. $authorize = Hash::normalize((array)$this->_config['authorize']);
  422. $global = array();
  423. if (isset($authorize[AuthComponent::ALL])) {
  424. $global = $authorize[AuthComponent::ALL];
  425. unset($authorize[AuthComponent::ALL]);
  426. }
  427. foreach ($authorize as $class => $config) {
  428. $className = App::className($class, 'Controller/Component/Auth', 'Authorize');
  429. if (!class_exists($className)) {
  430. throw new Error\Exception(sprintf('Authorization adapter "%s" was not found.', $class));
  431. }
  432. if (!method_exists($className, 'authorize')) {
  433. throw new Error\Exception('Authorization objects must implement an authorize() method.');
  434. }
  435. $config = array_merge($global, (array)$config);
  436. $this->_authorizeObjects[] = new $className($this->_registry, $config);
  437. }
  438. return $this->_authorizeObjects;
  439. }
  440. /**
  441. * Takes a list of actions in the current controller for which authentication is not required, or
  442. * no parameters to allow all actions.
  443. *
  444. * You can use allow with either an array or a simple string.
  445. *
  446. * `$this->Auth->allow('view');`
  447. * `$this->Auth->allow(['edit', 'add']);`
  448. * `$this->Auth->allow();` to allow all actions
  449. *
  450. * @param string|array $actions Controller action name or array of actions
  451. * @return void
  452. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
  453. */
  454. public function allow($actions = null) {
  455. if ($actions === null) {
  456. $this->allowedActions = $this->_methods;
  457. return;
  458. }
  459. $this->allowedActions = array_merge($this->allowedActions, (array)$actions);
  460. }
  461. /**
  462. * Removes items from the list of allowed/no authentication required actions.
  463. *
  464. * You can use deny with either an array or a simple string.
  465. *
  466. * `$this->Auth->deny('view');`
  467. * `$this->Auth->deny(['edit', 'add']);`
  468. * `$this->Auth->deny();` to remove all items from the allowed list
  469. *
  470. * @param string|array $actions Controller action name or array of actions
  471. * @return void
  472. * @see AuthComponent::allow()
  473. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
  474. */
  475. public function deny($actions = null) {
  476. if ($actions === null) {
  477. $this->allowedActions = array();
  478. return;
  479. }
  480. foreach ((array)$actions as $action) {
  481. $i = array_search($action, $this->allowedActions);
  482. if (is_int($i)) {
  483. unset($this->allowedActions[$i]);
  484. }
  485. }
  486. $this->allowedActions = array_values($this->allowedActions);
  487. }
  488. /**
  489. * Maps action names to CRUD operations.
  490. *
  491. * Used for controller-based authentication. Make sure
  492. * to configure the authorize property before calling this method. As it delegates $map to all the
  493. * attached authorize objects.
  494. *
  495. * @param array $map Actions to map
  496. * @return void
  497. * @see BaseAuthorize::mapActions()
  498. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
  499. */
  500. public function mapActions(array $map = array()) {
  501. if (empty($this->_authorizeObjects)) {
  502. $this->constructAuthorize();
  503. }
  504. foreach ($this->_authorizeObjects as $auth) {
  505. $auth->mapActions($map);
  506. }
  507. }
  508. /**
  509. * Log a user in.
  510. *
  511. * If a $user is provided that data will be stored as the logged in user. If `$user` is empty or not
  512. * specified, the request will be used to identify a user. If the identification was successful,
  513. * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
  514. * will also change the session id in order to help mitigate session replays.
  515. *
  516. * @param array $user Either an array of user data, or null to identify a user using the current request.
  517. * @return bool True on login success, false on failure
  518. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
  519. */
  520. public function login($user = null) {
  521. $this->_setDefaults();
  522. if (empty($user)) {
  523. $user = $this->identify($this->request, $this->response);
  524. }
  525. if ($user) {
  526. $this->Session->renew();
  527. $this->Session->write(static::$sessionKey, $user);
  528. }
  529. return (bool)$this->user();
  530. }
  531. /**
  532. * Log a user out.
  533. *
  534. * Returns the logout action to redirect to. Triggers the logout() method of
  535. * all the authenticate objects, so they can perform custom logout logic.
  536. * AuthComponent will remove the session data, so there is no need to do that
  537. * in an authentication object. Logging out will also renew the session id.
  538. * This helps mitigate issues with session replays.
  539. *
  540. * @return string Normalized config `logoutRedirect`
  541. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
  542. */
  543. public function logout() {
  544. $this->_setDefaults();
  545. if (empty($this->_authenticateObjects)) {
  546. $this->constructAuthenticate();
  547. }
  548. $user = (array)$this->user();
  549. foreach ($this->_authenticateObjects as $auth) {
  550. $auth->logout($user);
  551. }
  552. $this->Session->delete(static::$sessionKey);
  553. $this->Session->delete('Auth.redirect');
  554. $this->Session->renew();
  555. return Router::normalize($this->_config['logoutRedirect']);
  556. }
  557. /**
  558. * Get the current user.
  559. *
  560. * Will prefer the static user cache over sessions. The static user
  561. * cache is primarily used for stateless authentication. For stateful authentication,
  562. * cookies + sessions will be used.
  563. *
  564. * @param string $key field to retrieve. Leave null to get entire User record
  565. * @return mixed User record. or null if no user is logged in.
  566. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
  567. */
  568. public static function user($key = null) {
  569. if (!empty(static::$_user)) {
  570. $user = static::$_user;
  571. } elseif (static::$sessionKey && Session::check(static::$sessionKey)) {
  572. $user = Session::read(static::$sessionKey);
  573. } else {
  574. return null;
  575. }
  576. if ($key === null) {
  577. return $user;
  578. }
  579. return Hash::get($user, $key);
  580. }
  581. /**
  582. * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
  583. * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
  584. *
  585. * @return bool true if a user can be found, false if one cannot.
  586. */
  587. protected function _getUser() {
  588. $user = $this->user();
  589. if ($user) {
  590. $this->Session->delete('Auth.redirect');
  591. return true;
  592. }
  593. if (empty($this->_authenticateObjects)) {
  594. $this->constructAuthenticate();
  595. }
  596. foreach ($this->_authenticateObjects as $auth) {
  597. $result = $auth->getUser($this->request);
  598. if (!empty($result) && is_array($result)) {
  599. static::$_user = $result;
  600. return true;
  601. }
  602. }
  603. return false;
  604. }
  605. /**
  606. * Get the URL a user should be redirected to upon login.
  607. *
  608. * Pass a URL in to set the destination a user should be redirected to upon
  609. * logging in.
  610. *
  611. * If no parameter is passed, gets the authentication redirect URL. The URL
  612. * returned is as per following rules:
  613. *
  614. * - Returns the normalized URL from session Auth.redirect value if it is
  615. * present and for the same domain the current app is running on.
  616. * - If there is no session value and there is a config `loginRedirect`, the
  617. * `loginRedirect` value is returned.
  618. * - If there is no session and no `loginRedirect`, / is returned.
  619. *
  620. * @param string|array $url Optional URL to write as the login redirect URL.
  621. * @return string Redirect URL
  622. */
  623. public function redirectUrl($url = null) {
  624. if ($url !== null) {
  625. $redir = $url;
  626. $this->Session->write('Auth.redirect', $redir);
  627. } elseif ($this->Session->check('Auth.redirect')) {
  628. $redir = $this->Session->read('Auth.redirect');
  629. $this->Session->delete('Auth.redirect');
  630. if (Router::normalize($redir) === Router::normalize($this->_config['loginAction'])) {
  631. $redir = $this->_config['loginRedirect'];
  632. }
  633. } elseif ($this->_config['loginRedirect']) {
  634. $redir = $this->_config['loginRedirect'];
  635. } else {
  636. $redir = '/';
  637. }
  638. if (is_array($redir)) {
  639. return Router::url($redir + array('base' => false));
  640. }
  641. return $redir;
  642. }
  643. /**
  644. * Use the configured authentication adapters, and attempt to identify the user
  645. * by credentials contained in $request.
  646. *
  647. * @param \Cake\Network\Request $request The request that contains authentication data.
  648. * @param \Cake\Network\Response $response The response
  649. * @return array User record data, or false, if the user could not be identified.
  650. */
  651. public function identify(Request $request, Response $response) {
  652. if (empty($this->_authenticateObjects)) {
  653. $this->constructAuthenticate();
  654. }
  655. foreach ($this->_authenticateObjects as $auth) {
  656. $result = $auth->authenticate($request, $response);
  657. if (!empty($result) && is_array($result)) {
  658. return $result;
  659. }
  660. }
  661. return false;
  662. }
  663. /**
  664. * Loads the configured authentication objects.
  665. *
  666. * @return mixed either null on empty authenticate value, or an array of loaded objects.
  667. * @throws \Cake\Error\Exception
  668. */
  669. public function constructAuthenticate() {
  670. if (empty($this->_config['authenticate'])) {
  671. return;
  672. }
  673. $this->_authenticateObjects = array();
  674. $authenticate = Hash::normalize((array)$this->_config['authenticate']);
  675. $global = array();
  676. if (isset($authenticate[AuthComponent::ALL])) {
  677. $global = $authenticate[AuthComponent::ALL];
  678. unset($authenticate[AuthComponent::ALL]);
  679. }
  680. foreach ($authenticate as $class => $config) {
  681. $className = App::className($class, 'Controller/Component/Auth', 'Authenticate');
  682. if (!class_exists($className)) {
  683. throw new Error\Exception(sprintf('Authentication adapter "%s" was not found.', $class));
  684. }
  685. if (!method_exists($className, 'authenticate')) {
  686. throw new Error\Exception('Authentication objects must implement an authenticate() method.');
  687. }
  688. $config = array_merge($global, (array)$config);
  689. $this->_authenticateObjects[] = new $className($this->_registry, $config);
  690. }
  691. return $this->_authenticateObjects;
  692. }
  693. /**
  694. * Set a flash message. Uses the Session component, and values from `flash` config.
  695. *
  696. * @param string $message The message to set.
  697. * @return void
  698. */
  699. public function flash($message) {
  700. if ($message === false) {
  701. return;
  702. }
  703. $flashConfig = $this->_config['flash'];
  704. $this->Session->setFlash(
  705. $message,
  706. $flashConfig['element'],
  707. $flashConfig['params'],
  708. $flashConfig['key']
  709. );
  710. }
  711. }