AuthComponent.php 24 KB

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