AuthComponent.php 23 KB

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