PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Controller/Component/AuthComponent.php

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