PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/QuickApps/Cake/Controller/Component/AuthComponent.php

http://github.com/QuickAppsCMS/QuickApps-CMS
PHP | 726 lines | 330 code | 53 blank | 343 comment | 71 complexity | a87619464de5946ef1575d6ea3a0b911 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-3.0
  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. if ($controller->name == 'CakeError') {
  245. return true;
  246. }
  247. $methods = array_flip(array_map('strtolower', $controller->methods));
  248. $action = strtolower($controller->request->params['action']);
  249. $isMissingAction = (
  250. $controller->scaffold === false &&
  251. !isset($methods[$action])
  252. );
  253. if ($isMissingAction) {
  254. return true;
  255. }
  256. if (!$this->_setDefaults()) {
  257. return false;
  258. }
  259. $request = $controller->request;
  260. $url = '';
  261. if (isset($request->url)) {
  262. $url = $request->url;
  263. }
  264. $url = Router::normalize($url);
  265. $loginAction = Router::normalize($this->loginAction);
  266. $allowedActions = $this->allowedActions;
  267. $isAllowed = (
  268. $this->allowedActions == array('*') ||
  269. in_array($action, array_map('strtolower', $allowedActions))
  270. );
  271. if ($loginAction != $url && $isAllowed) {
  272. return true;
  273. }
  274. if ($loginAction == $url) {
  275. if (empty($request->data)) {
  276. if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
  277. $this->Session->write('Auth.redirect', $controller->referer(null, true));
  278. }
  279. }
  280. return true;
  281. } else {
  282. if (!$this->_getUser()) {
  283. if (!$request->is('ajax')) {
  284. $this->flash($this->authError);
  285. $this->Session->write('Auth.redirect', $request->here());
  286. $controller->redirect($loginAction);
  287. return false;
  288. } elseif (!empty($this->ajaxLogin)) {
  289. $controller->viewPath = 'Elements';
  290. echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
  291. $this->_stop();
  292. return false;
  293. } else {
  294. $controller->redirect(null, 403);
  295. }
  296. }
  297. }
  298. if (empty($this->authorize) || $this->isAuthorized($this->user())) {
  299. return true;
  300. }
  301. $this->flash($this->authError);
  302. $default = '/';
  303. if (!empty($this->loginRedirect)) {
  304. $default = $this->loginRedirect;
  305. }
  306. $controller->redirect($controller->referer($default), null, true);
  307. return false;
  308. }
  309. /**
  310. * Attempts to introspect the correct values for object properties.
  311. *
  312. * @return boolean
  313. */
  314. protected function _setDefaults() {
  315. $defaults = array(
  316. 'logoutRedirect' => $this->loginAction,
  317. 'authError' => __d('cake', 'You are not authorized to access that location.')
  318. );
  319. foreach ($defaults as $key => $value) {
  320. if (empty($this->{$key})) {
  321. $this->{$key} = $value;
  322. }
  323. }
  324. return true;
  325. }
  326. /**
  327. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  328. * Each adapter will be checked in sequence, if any of them return true, then the user will
  329. * be authorized for the request.
  330. *
  331. * @param mixed $user The user to check the authorization of. If empty the user in the session will be used.
  332. * @param CakeRequest $request The request to authenticate for. If empty, the current request will be used.
  333. * @return boolean True if $user is authorized, otherwise false
  334. */
  335. public function isAuthorized($user = null, $request = null) {
  336. if (empty($user) && !$this->user()) {
  337. return false;
  338. } elseif (empty($user)) {
  339. $user = $this->user();
  340. }
  341. if (empty($request)) {
  342. $request = $this->request;
  343. }
  344. if (empty($this->_authorizeObjects)) {
  345. $this->constructAuthorize();
  346. }
  347. foreach ($this->_authorizeObjects as $authorizer) {
  348. if ($authorizer->authorize($user, $request) === true) {
  349. return true;
  350. }
  351. }
  352. return false;
  353. }
  354. /**
  355. * Loads the authorization objects configured.
  356. *
  357. * @return mixed Either null when authorize is empty, or the loaded authorization objects.
  358. * @throws CakeException
  359. */
  360. public function constructAuthorize() {
  361. if (empty($this->authorize)) {
  362. return;
  363. }
  364. $this->_authorizeObjects = array();
  365. $config = Hash::normalize((array)$this->authorize);
  366. $global = array();
  367. if (isset($config[AuthComponent::ALL])) {
  368. $global = $config[AuthComponent::ALL];
  369. unset($config[AuthComponent::ALL]);
  370. }
  371. foreach ($config as $class => $settings) {
  372. list($plugin, $class) = pluginSplit($class, true);
  373. $className = $class . 'Authorize';
  374. App::uses($className, $plugin . 'Controller/Component/Auth');
  375. if (!class_exists($className)) {
  376. throw new CakeException(__d('cake_dev', 'Authorization adapter "%s" was not found.', $class));
  377. }
  378. if (!method_exists($className, 'authorize')) {
  379. throw new CakeException(__d('cake_dev', 'Authorization objects must implement an authorize method.'));
  380. }
  381. $settings = array_merge($global, (array)$settings);
  382. $this->_authorizeObjects[] = new $className($this->_Collection, $settings);
  383. }
  384. return $this->_authorizeObjects;
  385. }
  386. /**
  387. * Takes a list of actions in the current controller for which authentication is not required, or
  388. * no parameters to allow all actions.
  389. *
  390. * You can use allow with either an array, or var args.
  391. *
  392. * `$this->Auth->allow(array('edit', 'add'));` or
  393. * `$this->Auth->allow('edit', 'add');` or
  394. * `$this->Auth->allow();` to allow all actions
  395. *
  396. * @param mixed $action,... Controller action name or array of actions
  397. * @return void
  398. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
  399. */
  400. public function allow($action = null) {
  401. $args = func_get_args();
  402. if (empty($args) || $action === null) {
  403. $this->allowedActions = $this->_methods;
  404. } else {
  405. if (isset($args[0]) && is_array($args[0])) {
  406. $args = $args[0];
  407. }
  408. $this->allowedActions = array_merge($this->allowedActions, $args);
  409. }
  410. }
  411. /**
  412. * Removes items from the list of allowed/no authentication required actions.
  413. *
  414. * You can use deny with either an array, or var args.
  415. *
  416. * `$this->Auth->deny(array('edit', 'add'));` or
  417. * `$this->Auth->deny('edit', 'add');` or
  418. * `$this->Auth->deny();` to remove all items from the allowed list
  419. *
  420. * @param mixed $action,... Controller action name or array of actions
  421. * @return void
  422. * @see AuthComponent::allow()
  423. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
  424. */
  425. public function deny($action = null) {
  426. $args = func_get_args();
  427. if (empty($args) || $action === null) {
  428. $this->allowedActions = array();
  429. } else {
  430. if (isset($args[0]) && is_array($args[0])) {
  431. $args = $args[0];
  432. }
  433. foreach ($args as $arg) {
  434. $i = array_search($arg, $this->allowedActions);
  435. if (is_int($i)) {
  436. unset($this->allowedActions[$i]);
  437. }
  438. }
  439. $this->allowedActions = array_values($this->allowedActions);
  440. }
  441. }
  442. /**
  443. * Maps action names to CRUD operations. Used for controller-based authentication. Make sure
  444. * to configure the authorize property before calling this method. As it delegates $map to all the
  445. * attached authorize objects.
  446. *
  447. * @param array $map Actions to map
  448. * @return void
  449. * @see BaseAuthorize::mapActions()
  450. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
  451. */
  452. public function mapActions($map = array()) {
  453. if (empty($this->_authorizeObjects)) {
  454. $this->constructAuthorize();
  455. }
  456. foreach ($this->_authorizeObjects as $auth) {
  457. $auth->mapActions($map);
  458. }
  459. }
  460. /**
  461. * 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
  462. * specified, the request will be used to identify a user. If the identification was successful,
  463. * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
  464. * will also change the session id in order to help mitigate session replays.
  465. *
  466. * @param mixed $user Either an array of user data, or null to identify a user using the current request.
  467. * @return boolean True on login success, false on failure
  468. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
  469. */
  470. public function login($user = null) {
  471. $this->_setDefaults();
  472. if (empty($user)) {
  473. $user = $this->identify($this->request, $this->response);
  474. }
  475. if ($user) {
  476. $this->Session->renew();
  477. $this->Session->write(self::$sessionKey, $user);
  478. }
  479. return $this->loggedIn();
  480. }
  481. /**
  482. * Logs a user out, and returns the login action to redirect to.
  483. * Triggers the logout() method of all the authenticate objects, so they can perform
  484. * custom logout logic. AuthComponent will remove the session data, so
  485. * there is no need to do that in an authentication object. Logging out
  486. * will also renew the session id. This helps mitigate issues with session replays.
  487. *
  488. * @return string AuthComponent::$logoutRedirect
  489. * @see AuthComponent::$logoutRedirect
  490. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
  491. */
  492. public function logout() {
  493. $this->_setDefaults();
  494. if (empty($this->_authenticateObjects)) {
  495. $this->constructAuthenticate();
  496. }
  497. $user = $this->user();
  498. foreach ($this->_authenticateObjects as $auth) {
  499. $auth->logout($user);
  500. }
  501. $this->Session->delete(self::$sessionKey);
  502. $this->Session->delete('Auth.redirect');
  503. $this->Session->renew();
  504. return Router::normalize($this->logoutRedirect);
  505. }
  506. /**
  507. * Get the current user.
  508. *
  509. * Will prefer the static user cache over sessions. The static user
  510. * cache is primarily used for stateless authentication. For stateful authentication,
  511. * cookies + sessions will be used.
  512. *
  513. * @param string $key field to retrieve. Leave null to get entire User record
  514. * @return mixed User record. or null if no user is logged in.
  515. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
  516. */
  517. public static function user($key = null) {
  518. if (empty(self::$_user) && !CakeSession::check(self::$sessionKey)) {
  519. return null;
  520. }
  521. if (!empty(self::$_user)) {
  522. $user = self::$_user;
  523. } else {
  524. $user = CakeSession::read(self::$sessionKey);
  525. }
  526. if ($key === null) {
  527. return $user;
  528. }
  529. if (isset($user[$key])) {
  530. return $user[$key];
  531. }
  532. return null;
  533. }
  534. /**
  535. * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
  536. * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
  537. *
  538. * @return boolean true if a user can be found, false if one cannot.
  539. */
  540. protected function _getUser() {
  541. $user = $this->user();
  542. if ($user) {
  543. return true;
  544. }
  545. if (empty($this->_authenticateObjects)) {
  546. $this->constructAuthenticate();
  547. }
  548. foreach ($this->_authenticateObjects as $auth) {
  549. $result = $auth->getUser($this->request);
  550. if (!empty($result) && is_array($result)) {
  551. self::$_user = $result;
  552. return true;
  553. }
  554. }
  555. return false;
  556. }
  557. /**
  558. * If no parameter is passed, gets the authentication redirect URL. Pass a url in to
  559. * set the destination a user should be redirected to upon logging in. Will fallback to
  560. * AuthComponent::$loginRedirect if there is no stored redirect value.
  561. *
  562. * @param mixed $url Optional URL to write as the login redirect URL.
  563. * @return string Redirect URL
  564. */
  565. public function redirect($url = null) {
  566. if (!is_null($url)) {
  567. $redir = $url;
  568. $this->Session->write('Auth.redirect', $redir);
  569. } elseif ($this->Session->check('Auth.redirect')) {
  570. $redir = $this->Session->read('Auth.redirect');
  571. $this->Session->delete('Auth.redirect');
  572. if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
  573. $redir = $this->loginRedirect;
  574. }
  575. } else {
  576. $redir = $this->loginRedirect;
  577. }
  578. return Router::normalize($redir);
  579. }
  580. /**
  581. * Use the configured authentication adapters, and attempt to identify the user
  582. * by credentials contained in $request.
  583. *
  584. * @param CakeRequest $request The request that contains authentication data.
  585. * @param CakeResponse $response The response
  586. * @return array User record data, or false, if the user could not be identified.
  587. */
  588. public function identify(CakeRequest $request, CakeResponse $response) {
  589. if (empty($this->_authenticateObjects)) {
  590. $this->constructAuthenticate();
  591. }
  592. foreach ($this->_authenticateObjects as $auth) {
  593. $result = $auth->authenticate($request, $response);
  594. if (!empty($result) && is_array($result)) {
  595. return $result;
  596. }
  597. }
  598. return false;
  599. }
  600. /**
  601. * loads the configured authentication objects.
  602. *
  603. * @return mixed either null on empty authenticate value, or an array of loaded objects.
  604. * @throws CakeException
  605. */
  606. public function constructAuthenticate() {
  607. if (empty($this->authenticate)) {
  608. return;
  609. }
  610. $this->_authenticateObjects = array();
  611. $config = Hash::normalize((array)$this->authenticate);
  612. $global = array();
  613. if (isset($config[AuthComponent::ALL])) {
  614. $global = $config[AuthComponent::ALL];
  615. unset($config[AuthComponent::ALL]);
  616. }
  617. foreach ($config as $class => $settings) {
  618. list($plugin, $class) = pluginSplit($class, true);
  619. $className = $class . 'Authenticate';
  620. App::uses($className, $plugin . 'Controller/Component/Auth');
  621. if (!class_exists($className)) {
  622. throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class));
  623. }
  624. if (!method_exists($className, 'authenticate')) {
  625. throw new CakeException(__d('cake_dev', 'Authentication objects must implement an authenticate method.'));
  626. }
  627. $settings = array_merge($global, (array)$settings);
  628. $this->_authenticateObjects[] = new $className($this->_Collection, $settings);
  629. }
  630. return $this->_authenticateObjects;
  631. }
  632. /**
  633. * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
  634. *
  635. * This method is intended as a convenience wrapper for Security::hash(). If you want to use
  636. * a hashing/encryption system not supported by that method, do not use this method.
  637. *
  638. * @param string $password Password to hash
  639. * @return string Hashed password
  640. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords
  641. */
  642. public static function password($password) {
  643. return Security::hash($password, null, true);
  644. }
  645. /**
  646. * Component shutdown. If user is logged in, wipe out redirect.
  647. *
  648. * @param Controller $controller Instantiating controller
  649. * @return void
  650. */
  651. public function shutdown(Controller $controller) {
  652. if ($this->loggedIn()) {
  653. $this->Session->delete('Auth.redirect');
  654. }
  655. }
  656. /**
  657. * Check whether or not the current user has data in the session, and is considered logged in.
  658. *
  659. * @return boolean true if the user is logged in, false otherwise
  660. */
  661. public function loggedIn() {
  662. return $this->user() != array();
  663. }
  664. /**
  665. * Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
  666. *
  667. * @param string $message The message to set.
  668. * @return void
  669. */
  670. public function flash($message) {
  671. $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']);
  672. }
  673. }