AuthComponent.php 25 KB

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