AuthComponent.php 20 KB

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