AuthComponent.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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/view/1250/Authentication
  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/view/1278/authenticate
  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. * @link http://book.cakephp.org/view/1277/ajaxLogin
  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. * @link http://book.cakephp.org/view/1276/sessionKey
  150. */
  151. public static $sessionKey = 'Auth.User';
  152. /**
  153. * A URL (defined as a string or array) to the controller action that handles
  154. * logins. Defaults to `/users/login`
  155. *
  156. * @var mixed
  157. * @link http://book.cakephp.org/view/1269/loginAction
  158. */
  159. public $loginAction = array(
  160. 'controller' => 'users',
  161. 'action' => 'login',
  162. 'plugin' => null
  163. );
  164. /**
  165. * Normally, if a user is redirected to the $loginAction page, the location they
  166. * were redirected from will be stored in the session so that they can be
  167. * redirected back after a successful login. If this session value is not
  168. * set, the user will be redirected to the page specified in $loginRedirect.
  169. *
  170. * @var mixed
  171. * @link http://book.cakephp.org/view/1270/loginRedirect
  172. */
  173. public $loginRedirect = null;
  174. /**
  175. * The default action to redirect to after the user is logged out. While AuthComponent does
  176. * not handle post-logout redirection, a redirect URL will be returned from AuthComponent::logout().
  177. * Defaults to AuthComponent::$loginAction.
  178. *
  179. * @var mixed
  180. * @see AuthComponent::$loginAction
  181. * @see AuthComponent::logout()
  182. * @link http://book.cakephp.org/view/1271/logoutRedirect
  183. */
  184. public $logoutRedirect = null;
  185. /**
  186. * Error to display when user attempts to access an object or action to which they do not have
  187. * acccess.
  188. *
  189. * @var string
  190. * @link http://book.cakephp.org/view/1273/authError
  191. */
  192. public $authError = null;
  193. /**
  194. * Controller actions for which user validation is not required.
  195. *
  196. * @var array
  197. * @see AuthComponent::allow()
  198. * @link http://book.cakephp.org/view/1251/Setting-Auth-Component-Variables
  199. */
  200. public $allowedActions = array();
  201. /**
  202. * Request object
  203. *
  204. * @var CakeRequest
  205. */
  206. public $request;
  207. /**
  208. * Response object
  209. *
  210. * @var CakeResponse
  211. */
  212. public $response;
  213. /**
  214. * Method list for bound controller
  215. *
  216. * @var array
  217. */
  218. protected $_methods = array();
  219. /**
  220. * Initializes AuthComponent for use in the controller
  221. *
  222. * @param Controller $controller A reference to the instantiating controller object
  223. * @return void
  224. */
  225. public function initialize($controller) {
  226. $this->request = $controller->request;
  227. $this->response = $controller->response;
  228. $this->_methods = $controller->methods;
  229. if (Configure::read('debug') > 0) {
  230. Debugger::checkSecurityKeys();
  231. }
  232. }
  233. /**
  234. * Main execution method. Handles redirecting of invalid users, and processing
  235. * of login form data.
  236. *
  237. * @param Controller $controller A reference to the instantiating controller object
  238. * @return boolean
  239. */
  240. public function startup($controller) {
  241. if ($controller->name == 'CakeError') {
  242. return true;
  243. }
  244. $methods = array_flip($controller->methods);
  245. $action = $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, $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', Router::reverse($request));
  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. $controller->redirect($controller->referer('/'), null, true);
  300. return false;
  301. }
  302. /**
  303. * Attempts to introspect the correct values for object properties including
  304. * $userModel and $sessionKey.
  305. *
  306. * @return boolean
  307. */
  308. protected function _setDefaults() {
  309. $defaults = array(
  310. 'logoutRedirect' => $this->loginAction,
  311. 'authError' => __d('cake', 'You are not authorized to access that location.')
  312. );
  313. foreach ($defaults as $key => $value) {
  314. if (empty($this->{$key})) {
  315. $this->{$key} = $value;
  316. }
  317. }
  318. return true;
  319. }
  320. /**
  321. * Uses the configured Authorization adapters to check whether or not a user is authorized.
  322. * Each adapter will be checked in sequence, if any of them return true, then the user will
  323. * be authorized for the request.
  324. *
  325. * @param mixed $user The user to check the authorization of. If empty the user in the session will be used.
  326. * @param CakeRequest $request The request to authenticate for. If empty, the current request will be used.
  327. * @return boolean True if $user is authorized, otherwise false
  328. */
  329. public function isAuthorized($user = null, $request = null) {
  330. if (empty($user) && !$this->user()) {
  331. return false;
  332. } elseif (empty($user)) {
  333. $user = $this->user();
  334. }
  335. if (empty($request)) {
  336. $request = $this->request;
  337. }
  338. if (empty($this->_authorizeObjects)) {
  339. $this->constructAuthorize();
  340. }
  341. foreach ($this->_authorizeObjects as $authorizer) {
  342. if ($authorizer->authorize($user, $request) === true) {
  343. return true;
  344. }
  345. }
  346. return false;
  347. }
  348. /**
  349. * Loads the authorization objects configured.
  350. *
  351. * @return mixed Either null when authorize is empty, or the loaded authorization objects.
  352. * @throws CakeException
  353. */
  354. public function constructAuthorize() {
  355. if (empty($this->authorize)) {
  356. return;
  357. }
  358. $this->_authorizeObjects = array();
  359. $config = Set::normalize($this->authorize);
  360. $global = array();
  361. if (isset($config[AuthComponent::ALL])) {
  362. $global = $config[AuthComponent::ALL];
  363. unset($config[AuthComponent::ALL]);
  364. }
  365. foreach ($config as $class => $settings) {
  366. list($plugin, $class) = pluginSplit($class, true);
  367. $className = $class . 'Authorize';
  368. App::uses($className, $plugin . 'Controller/Component/Auth');
  369. if (!class_exists($className)) {
  370. throw new CakeException(__d('cake_dev', 'Authorization adapter "%s" was not found.', $class));
  371. }
  372. if (!method_exists($className, 'authorize')) {
  373. throw new CakeException(__d('cake_dev', 'Authorization objects must implement an authorize method.'));
  374. }
  375. $settings = array_merge($global, (array)$settings);
  376. $this->_authorizeObjects[] = new $className($this->_Collection, $settings);
  377. }
  378. return $this->_authorizeObjects;
  379. }
  380. /**
  381. * Takes a list of actions in the current controller for which authentication is not required, or
  382. * no parameters to allow all actions.
  383. *
  384. * You can use allow with either an array, or var args.
  385. *
  386. * `$this->Auth->allow(array('edit', 'add'));` or
  387. * `$this->Auth->allow('edit', 'add');`
  388. *
  389. * allow() also supports '*' as a wildcard to mean all actions.
  390. *
  391. * `$this->Auth->allow('*');`
  392. *
  393. * @param mixed $action,... Controller action name or array of actions
  394. * @return void
  395. * @link http://book.cakephp.org/view/1257/allow
  396. */
  397. public function allow($action = null) {
  398. $args = func_get_args();
  399. if (empty($args) || $args == array('*')) {
  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');`
  415. *
  416. * @param mixed $action,... Controller action name or array of actions
  417. * @return void
  418. * @see AuthComponent::allow()
  419. * @link http://book.cakephp.org/view/1258/deny
  420. */
  421. public function deny($action = null) {
  422. $args = func_get_args();
  423. if (isset($args[0]) && is_array($args[0])) {
  424. $args = $args[0];
  425. }
  426. foreach ($args as $arg) {
  427. $i = array_search($arg, $this->allowedActions);
  428. if (is_int($i)) {
  429. unset($this->allowedActions[$i]);
  430. }
  431. }
  432. $this->allowedActions = array_values($this->allowedActions);
  433. }
  434. /**
  435. * Maps action names to CRUD operations. Used for controller-based authentication. Make sure
  436. * to configure the authorize property before calling this method. As it delegates $map to all the
  437. * attached authorize objects.
  438. *
  439. * @param array $map Actions to map
  440. * @return void
  441. * @see BaseAuthorize::mapActions()
  442. */
  443. public function mapActions($map = array()) {
  444. if (empty($this->_authorizeObjects)) {
  445. $this->constructAuthorize();
  446. }
  447. foreach ($this->_authorizeObjects as $auth) {
  448. $auth->mapActions($map);
  449. }
  450. }
  451. /**
  452. * 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
  453. * specified, the request will be used to identify a user. If the identification was successful,
  454. * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
  455. * will also change the session id in order to help mitigate session replays.
  456. *
  457. * @param mixed $user Either an array of user data, or null to identify a user using the current request.
  458. * @return boolean True on login success, false on failure
  459. * @link http://book.cakephp.org/view/1261/login
  460. */
  461. public function login($user = null) {
  462. $this->_setDefaults();
  463. if (empty($user)) {
  464. $user = $this->identify($this->request, $this->response);
  465. }
  466. if ($user) {
  467. $this->Session->renew();
  468. $this->Session->write(self::$sessionKey, $user);
  469. }
  470. return $this->loggedIn();
  471. }
  472. /**
  473. * Logs a user out, and returns the login action to redirect to.
  474. * Triggers the logout() method of all the authenticate objects, so they can perform
  475. * custom logout logic. AuthComponent will remove the session data, so
  476. * there is no need to do that in an authentication object. Logging out
  477. * will also renew the session id. This helps mitigate issues with session replays.
  478. *
  479. * @return string AuthComponent::$logoutRedirect
  480. * @see AuthComponent::$logoutRedirect
  481. * @link http://book.cakephp.org/view/1262/logout
  482. */
  483. public function logout() {
  484. $this->_setDefaults();
  485. if (empty($this->_authenticateObjects)) {
  486. $this->constructAuthenticate();
  487. }
  488. $user = $this->user();
  489. foreach ($this->_authenticateObjects as $auth) {
  490. $auth->logout($user);
  491. }
  492. $this->Session->delete(self::$sessionKey);
  493. $this->Session->delete('Auth.redirect');
  494. $this->Session->renew();
  495. return Router::normalize($this->logoutRedirect);
  496. }
  497. /**
  498. * Get the current user from the session.
  499. *
  500. * @param string $key field to retrive. Leave null to get entire User record
  501. * @return mixed User record. or null if no user is logged in.
  502. * @link http://book.cakephp.org/view/1264/user
  503. */
  504. public static function user($key = null) {
  505. if (!CakeSession::check(self::$sessionKey)) {
  506. return null;
  507. }
  508. if ($key == null) {
  509. return CakeSession::read(self::$sessionKey);
  510. }
  511. $user = CakeSession::read(self::$sessionKey);
  512. if (isset($user[$key])) {
  513. return $user[$key];
  514. }
  515. return null;
  516. }
  517. /**
  518. * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
  519. * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
  520. *
  521. * @return boolean true if a user can be found, false if one cannot.
  522. */
  523. protected function _getUser() {
  524. $user = $this->user();
  525. if ($user) {
  526. return true;
  527. }
  528. if (empty($this->_authenticateObjects)) {
  529. $this->constructAuthenticate();
  530. }
  531. foreach ($this->_authenticateObjects as $auth) {
  532. $result = $auth->getUser($this->request);
  533. if (!empty($result) && is_array($result)) {
  534. return true;
  535. }
  536. }
  537. return false;
  538. }
  539. /**
  540. * If no parameter is passed, gets the authentication redirect URL. Pass a url in to
  541. * set the destination a user should be redirected to upon logging in. Will fallback to
  542. * AuthComponent::$loginRedirect if there is no stored redirect value.
  543. *
  544. * @param mixed $url Optional URL to write as the login redirect URL.
  545. * @return string Redirect URL
  546. */
  547. public function redirect($url = null) {
  548. if (!is_null($url)) {
  549. $redir = $url;
  550. $this->Session->write('Auth.redirect', $redir);
  551. } elseif ($this->Session->check('Auth.redirect')) {
  552. $redir = $this->Session->read('Auth.redirect');
  553. $this->Session->delete('Auth.redirect');
  554. if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
  555. $redir = $this->loginRedirect;
  556. }
  557. } else {
  558. $redir = $this->loginRedirect;
  559. }
  560. return Router::normalize($redir);
  561. }
  562. /**
  563. * Use the configured authentication adapters, and attempt to identify the user
  564. * by credentials contained in $request.
  565. *
  566. * @param CakeRequest $request The request that contains authentication data.
  567. * @param CakeResponse $response The response
  568. * @return array User record data, or false, if the user could not be identified.
  569. */
  570. public function identify(CakeRequest $request, CakeResponse $response) {
  571. if (empty($this->_authenticateObjects)) {
  572. $this->constructAuthenticate();
  573. }
  574. foreach ($this->_authenticateObjects as $auth) {
  575. $result = $auth->authenticate($request, $response);
  576. if (!empty($result) && is_array($result)) {
  577. return $result;
  578. }
  579. }
  580. return false;
  581. }
  582. /**
  583. * loads the configured authentication objects.
  584. *
  585. * @return mixed either null on empty authenticate value, or an array of loaded objects.
  586. * @throws CakeException
  587. */
  588. public function constructAuthenticate() {
  589. if (empty($this->authenticate)) {
  590. return;
  591. }
  592. $this->_authenticateObjects = array();
  593. $config = Set::normalize($this->authenticate);
  594. $global = array();
  595. if (isset($config[AuthComponent::ALL])) {
  596. $global = $config[AuthComponent::ALL];
  597. unset($config[AuthComponent::ALL]);
  598. }
  599. foreach ($config as $class => $settings) {
  600. list($plugin, $class) = pluginSplit($class, true);
  601. $className = $class . 'Authenticate';
  602. App::uses($className, $plugin . 'Controller/Component/Auth');
  603. if (!class_exists($className)) {
  604. throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class));
  605. }
  606. if (!method_exists($className, 'authenticate')) {
  607. throw new CakeException(__d('cake_dev', 'Authentication objects must implement an authenticate method.'));
  608. }
  609. $settings = array_merge($global, (array)$settings);
  610. $this->_authenticateObjects[] = new $className($this->_Collection, $settings);
  611. }
  612. return $this->_authenticateObjects;
  613. }
  614. /**
  615. * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
  616. *
  617. * This method is intended as a convenience wrapper for Security::hash(). If you want to use
  618. * a hashing/encryption system not supported by that method, do not use this method.
  619. *
  620. * @param string $password Password to hash
  621. * @return string Hashed password
  622. * @link http://book.cakephp.org/view/1263/password
  623. */
  624. public static function password($password) {
  625. return Security::hash($password, null, true);
  626. }
  627. /**
  628. * Component shutdown. If user is logged in, wipe out redirect.
  629. *
  630. * @param Controller $controller Instantiating controller
  631. * @return void
  632. */
  633. public function shutdown($controller) {
  634. if ($this->loggedIn()) {
  635. $this->Session->delete('Auth.redirect');
  636. }
  637. }
  638. /**
  639. * Check whether or not the current user has data in the session, and is considered logged in.
  640. *
  641. * @return boolean true if the user is logged in, false otherwise
  642. */
  643. public function loggedIn() {
  644. return $this->user() != array();
  645. }
  646. /**
  647. * Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
  648. *
  649. * @param string $message The message to set.
  650. * @return void
  651. */
  652. public function flash($message) {
  653. $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']);
  654. }
  655. }