PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

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

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