AuthComponent.php 23 KB

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