AuthComponent.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. <?php
  2. /**
  3. * Authentication component
  4. *
  5. * Manages user logins and permissions.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * For full copyright and license information, please see the LICENSE.txt
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package Cake.Controller.Component
  19. * @since CakePHP(tm) v 0.10.0.1076
  20. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  21. */
  22. App::uses('Component', 'Controller');
  23. App::uses('Router', 'Routing');
  24. App::uses('Security', 'Utility');
  25. App::uses('Debugger', 'Utility');
  26. App::uses('Hash', 'Utility');
  27. App::uses('CakeSession', 'Model/Datasource');
  28. App::uses('BaseAuthorize', 'Controller/Component/Auth');
  29. App::uses('BaseAuthenticate', 'Controller/Component/Auth');
  30. /**
  31. * Authentication control component class
  32. *
  33. * Binds access control with user authentication and session management.
  34. *
  35. * @package Cake.Controller.Component
  36. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
  37. */
  38. class AuthComponent extends Component {
  39. /**
  40. * Constant for 'all'
  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. * An 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|boolean Error message or boolean false to suppress flash message
  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 an 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 boolean
  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 boolean 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 boolean 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->viewPath = 'Elements';
  334. echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
  335. $this->_stop();
  336. return false;
  337. }
  338. $controller->redirect(null, 403);
  339. return false;
  340. }
  341. /**
  342. * Normalizes $loginAction and checks if current request URL is same as login action.
  343. *
  344. * @param Controller $controller A reference to the controller object.
  345. * @return boolean True if current action is login action else false.
  346. */
  347. protected function _isLoginAction(Controller $controller) {
  348. $url = '';
  349. if (isset($controller->request->url)) {
  350. $url = $controller->request->url;
  351. }
  352. $url = Router::normalize($url);
  353. $loginAction = Router::normalize($this->loginAction);
  354. return $loginAction === $url;
  355. }
  356. /**
  357. * Handle unauthorized access attempt
  358. *
  359. * @param Controller $controller A reference to the controller object
  360. * @return boolean Returns false
  361. * @throws ForbiddenException
  362. * @see AuthComponent::$unauthorizedRedirect
  363. */
  364. protected function _unauthorized(Controller $controller) {
  365. if ($this->unauthorizedRedirect === false) {
  366. throw new ForbiddenException($this->authError);
  367. }
  368. $this->flash($this->authError);
  369. if ($this->unauthorizedRedirect === true) {
  370. $default = '/';
  371. if (!empty($this->loginRedirect)) {
  372. $default = $this->loginRedirect;
  373. }
  374. $url = $controller->referer($default, true);
  375. } else {
  376. $url = $this->unauthorizedRedirect;
  377. }
  378. $controller->redirect($url, null, true);
  379. return false;
  380. }
  381. /**
  382. * Attempts to introspect the correct values for object properties.
  383. *
  384. * @return boolean True
  385. */
  386. protected function _setDefaults() {
  387. $defaults = array(
  388. 'logoutRedirect' => $this->loginAction,
  389. 'authError' => __d('cake', 'You are not authorized to access that location.')
  390. );
  391. foreach ($defaults as $key => $value) {
  392. if (!isset($this->{$key}) || $this->{$key} === true) {
  393. $this->{$key} = $value;
  394. }
  395. }
  396. return true;
  397. }
  398. /**
  399. * Check if the provided user is authorized for the request.
  400. *
  401. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  402. * Each adapter will be checked in sequence, if any of them return true, then the user will
  403. * be authorized for the request.
  404. *
  405. * @param array $user The user to check the authorization of. If empty the user in the session will be used.
  406. * @param CakeRequest $request The request to authenticate for. If empty, the current request will be used.
  407. * @return boolean True if $user is authorized, otherwise false
  408. */
  409. public function isAuthorized($user = null, CakeRequest $request = null) {
  410. if (empty($user) && !$this->user()) {
  411. return false;
  412. }
  413. if (empty($user)) {
  414. $user = $this->user();
  415. }
  416. if (empty($request)) {
  417. $request = $this->request;
  418. }
  419. if (empty($this->_authorizeObjects)) {
  420. $this->constructAuthorize();
  421. }
  422. foreach ($this->_authorizeObjects as $authorizer) {
  423. if ($authorizer->authorize($user, $request) === true) {
  424. return true;
  425. }
  426. }
  427. return false;
  428. }
  429. /**
  430. * Loads the authorization objects configured.
  431. *
  432. * @return mixed Either null when authorize is empty, or the loaded authorization objects.
  433. * @throws CakeException
  434. */
  435. public function constructAuthorize() {
  436. if (empty($this->authorize)) {
  437. return;
  438. }
  439. $this->_authorizeObjects = array();
  440. $config = Hash::normalize((array)$this->authorize);
  441. $global = array();
  442. if (isset($config[AuthComponent::ALL])) {
  443. $global = $config[AuthComponent::ALL];
  444. unset($config[AuthComponent::ALL]);
  445. }
  446. foreach ($config as $class => $settings) {
  447. list($plugin, $class) = pluginSplit($class, true);
  448. $className = $class . 'Authorize';
  449. App::uses($className, $plugin . 'Controller/Component/Auth');
  450. if (!class_exists($className)) {
  451. throw new CakeException(__d('cake_dev', 'Authorization adapter "%s" was not found.', $class));
  452. }
  453. if (!method_exists($className, 'authorize')) {
  454. throw new CakeException(__d('cake_dev', 'Authorization objects must implement an %s method.', 'authorize()'));
  455. }
  456. $settings = array_merge($global, (array)$settings);
  457. $this->_authorizeObjects[] = new $className($this->_Collection, $settings);
  458. }
  459. return $this->_authorizeObjects;
  460. }
  461. /**
  462. * Takes a list of actions in the current controller for which authentication is not required, or
  463. * no parameters to allow all actions.
  464. *
  465. * You can use allow with either an array, or var args.
  466. *
  467. * `$this->Auth->allow(array('edit', 'add'));` or
  468. * `$this->Auth->allow('edit', 'add');` or
  469. * `$this->Auth->allow();` to allow all actions
  470. *
  471. * @param string|array $action,... Controller action name or array of actions
  472. * @return void
  473. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
  474. */
  475. public function allow($action = null) {
  476. $args = func_get_args();
  477. if (empty($args) || $action === null) {
  478. $this->allowedActions = $this->_methods;
  479. return;
  480. }
  481. if (isset($args[0]) && is_array($args[0])) {
  482. $args = $args[0];
  483. }
  484. $this->allowedActions = array_merge($this->allowedActions, $args);
  485. }
  486. /**
  487. * Removes items from the list of allowed/no authentication required actions.
  488. *
  489. * You can use deny with either an array, or var args.
  490. *
  491. * `$this->Auth->deny(array('edit', 'add'));` or
  492. * `$this->Auth->deny('edit', 'add');` or
  493. * `$this->Auth->deny();` to remove all items from the allowed list
  494. *
  495. * @param string|array $action,... Controller action name or array of actions
  496. * @return void
  497. * @see AuthComponent::allow()
  498. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
  499. */
  500. public function deny($action = null) {
  501. $args = func_get_args();
  502. if (empty($args) || $action === null) {
  503. $this->allowedActions = array();
  504. return;
  505. }
  506. if (isset($args[0]) && is_array($args[0])) {
  507. $args = $args[0];
  508. }
  509. foreach ($args as $arg) {
  510. $i = array_search($arg, $this->allowedActions);
  511. if (is_int($i)) {
  512. unset($this->allowedActions[$i]);
  513. }
  514. }
  515. $this->allowedActions = array_values($this->allowedActions);
  516. }
  517. /**
  518. * Maps action names to CRUD operations.
  519. *
  520. * Used for controller-based authentication. Make sure
  521. * to configure the authorize property before calling this method. As it delegates $map to all the
  522. * attached authorize objects.
  523. *
  524. * @param array $map Actions to map
  525. * @return void
  526. * @see BaseAuthorize::mapActions()
  527. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
  528. */
  529. public function mapActions($map = array()) {
  530. if (empty($this->_authorizeObjects)) {
  531. $this->constructAuthorize();
  532. }
  533. foreach ($this->_authorizeObjects as $auth) {
  534. $auth->mapActions($map);
  535. }
  536. }
  537. /**
  538. * Log a user in.
  539. *
  540. * If a $user is provided that data will be stored as the logged in user. If `$user` is empty or not
  541. * specified, the request will be used to identify a user. If the identification was successful,
  542. * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
  543. * will also change the session id in order to help mitigate session replays.
  544. *
  545. * @param array $user Either an array of user data, or null to identify a user using the current request.
  546. * @return boolean True on login success, false on failure
  547. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
  548. */
  549. public function login($user = null) {
  550. $this->_setDefaults();
  551. if (empty($user)) {
  552. $user = $this->identify($this->request, $this->response);
  553. }
  554. if ($user) {
  555. $this->Session->renew();
  556. $this->Session->write(self::$sessionKey, $user);
  557. }
  558. return $this->loggedIn();
  559. }
  560. /**
  561. * Log a user out.
  562. *
  563. * Returns the logout action to redirect to. Triggers the logout() method of
  564. * all the authenticate objects, so they can perform custom logout logic.
  565. * AuthComponent will remove the session data, so there is no need to do that
  566. * in an authentication object. Logging out will also renew the session id.
  567. * This helps mitigate issues with session replays.
  568. *
  569. * @return string AuthComponent::$logoutRedirect
  570. * @see AuthComponent::$logoutRedirect
  571. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
  572. */
  573. public function logout() {
  574. $this->_setDefaults();
  575. if (empty($this->_authenticateObjects)) {
  576. $this->constructAuthenticate();
  577. }
  578. $user = $this->user();
  579. foreach ($this->_authenticateObjects as $auth) {
  580. $auth->logout($user);
  581. }
  582. $this->Session->delete(self::$sessionKey);
  583. $this->Session->delete('Auth.redirect');
  584. $this->Session->renew();
  585. return Router::normalize($this->logoutRedirect);
  586. }
  587. /**
  588. * Get the current user.
  589. *
  590. * Will prefer the static user cache over sessions. The static user
  591. * cache is primarily used for stateless authentication. For stateful authentication,
  592. * cookies + sessions will be used.
  593. *
  594. * @param string $key field to retrieve. Leave null to get entire User record
  595. * @return mixed User record. or null if no user is logged in.
  596. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
  597. */
  598. public static function user($key = null) {
  599. if (!empty(self::$_user)) {
  600. $user = self::$_user;
  601. } elseif (self::$sessionKey && CakeSession::check(self::$sessionKey)) {
  602. $user = CakeSession::read(self::$sessionKey);
  603. } else {
  604. return null;
  605. }
  606. if ($key === null) {
  607. return $user;
  608. }
  609. return Hash::get($user, $key);
  610. }
  611. /**
  612. * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
  613. * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
  614. *
  615. * @return boolean true if a user can be found, false if one cannot.
  616. */
  617. protected function _getUser() {
  618. $user = $this->user();
  619. if ($user) {
  620. $this->Session->delete('Auth.redirect');
  621. return true;
  622. }
  623. if (empty($this->_authenticateObjects)) {
  624. $this->constructAuthenticate();
  625. }
  626. foreach ($this->_authenticateObjects as $auth) {
  627. $result = $auth->getUser($this->request);
  628. if (!empty($result) && is_array($result)) {
  629. self::$_user = $result;
  630. return true;
  631. }
  632. }
  633. return false;
  634. }
  635. /**
  636. * Backwards compatible alias for AuthComponent::redirectUrl().
  637. *
  638. * @param string|array $url Optional URL to write as the login redirect URL.
  639. * @return string Redirect URL
  640. * @deprecated 2.3 Use AuthComponent::redirectUrl() instead
  641. */
  642. public function redirect($url = null) {
  643. return $this->redirectUrl($url);
  644. }
  645. /**
  646. * Get the URL a user should be redirected to upon login.
  647. *
  648. * Pass an URL in to set the destination a user should be redirected to upon
  649. * logging in.
  650. *
  651. * If no parameter is passed, gets the authentication redirect URL. The URL
  652. * returned is as per following rules:
  653. *
  654. * - Returns the normalized URL from session Auth.redirect value if it is
  655. * present and for the same domain the current app is running on.
  656. * - If there is no session value and there is a $loginRedirect, the $loginRedirect
  657. * value is returned.
  658. * - If there is no session and no $loginRedirect, / is returned.
  659. *
  660. * @param string|array $url Optional URL to write as the login redirect URL.
  661. * @return string Redirect URL
  662. */
  663. public function redirectUrl($url = null) {
  664. if ($url !== null) {
  665. $redir = $url;
  666. $this->Session->write('Auth.redirect', $redir);
  667. } elseif ($this->Session->check('Auth.redirect')) {
  668. $redir = $this->Session->read('Auth.redirect');
  669. $this->Session->delete('Auth.redirect');
  670. if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
  671. $redir = $this->loginRedirect;
  672. }
  673. } elseif ($this->loginRedirect) {
  674. $redir = $this->loginRedirect;
  675. } else {
  676. $redir = '/';
  677. }
  678. if (is_array($redir)) {
  679. return Router::url($redir + array('base' => false));
  680. }
  681. return $redir;
  682. }
  683. /**
  684. * Use the configured authentication adapters, and attempt to identify the user
  685. * by credentials contained in $request.
  686. *
  687. * @param CakeRequest $request The request that contains authentication data.
  688. * @param CakeResponse $response The response
  689. * @return array User record data, or false, if the user could not be identified.
  690. */
  691. public function identify(CakeRequest $request, CakeResponse $response) {
  692. if (empty($this->_authenticateObjects)) {
  693. $this->constructAuthenticate();
  694. }
  695. foreach ($this->_authenticateObjects as $auth) {
  696. $result = $auth->authenticate($request, $response);
  697. if (!empty($result) && is_array($result)) {
  698. return $result;
  699. }
  700. }
  701. return false;
  702. }
  703. /**
  704. * Loads the configured authentication objects.
  705. *
  706. * @return mixed either null on empty authenticate value, or an array of loaded objects.
  707. * @throws CakeException
  708. */
  709. public function constructAuthenticate() {
  710. if (empty($this->authenticate)) {
  711. return;
  712. }
  713. $this->_authenticateObjects = array();
  714. $config = Hash::normalize((array)$this->authenticate);
  715. $global = array();
  716. if (isset($config[AuthComponent::ALL])) {
  717. $global = $config[AuthComponent::ALL];
  718. unset($config[AuthComponent::ALL]);
  719. }
  720. foreach ($config as $class => $settings) {
  721. list($plugin, $class) = pluginSplit($class, true);
  722. $className = $class . 'Authenticate';
  723. App::uses($className, $plugin . 'Controller/Component/Auth');
  724. if (!class_exists($className)) {
  725. throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class));
  726. }
  727. if (!method_exists($className, 'authenticate')) {
  728. throw new CakeException(__d('cake_dev', 'Authentication objects must implement an %s method.', 'authenticate()'));
  729. }
  730. $settings = array_merge($global, (array)$settings);
  731. $this->_authenticateObjects[] = new $className($this->_Collection, $settings);
  732. }
  733. return $this->_authenticateObjects;
  734. }
  735. /**
  736. * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
  737. *
  738. * This method is intended as a convenience wrapper for Security::hash(). If you want to use
  739. * a hashing/encryption system not supported by that method, do not use this method.
  740. *
  741. * @param string $password Password to hash
  742. * @return string Hashed password
  743. * @deprecated Since 2.4. Use Security::hash() directly or a password hasher object.
  744. */
  745. public static function password($password) {
  746. return Security::hash($password, null, true);
  747. }
  748. /**
  749. * Check whether or not the current user has data in the session, and is considered logged in.
  750. *
  751. * @return boolean true if the user is logged in, false otherwise
  752. */
  753. public function loggedIn() {
  754. return (bool)$this->user();
  755. }
  756. /**
  757. * Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
  758. *
  759. * @param string $message The message to set.
  760. * @return void
  761. */
  762. public function flash($message) {
  763. if ($message === false) {
  764. return;
  765. }
  766. $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']);
  767. }
  768. }