AuthComponent.php 25 KB

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