AuthComponent.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. /**
  26. * Authentication control component class
  27. *
  28. * Binds access control with user authentication and session management.
  29. *
  30. * @package cake.libs.controller.components
  31. * @link http://book.cakephp.org/view/1250/Authentication
  32. */
  33. class AuthComponent extends Component {
  34. /**
  35. * Maintains current user login state.
  36. *
  37. * @var boolean
  38. */
  39. protected $_loggedIn = false;
  40. /**
  41. * Other components utilized by AuthComponent
  42. *
  43. * @var array
  44. */
  45. public $components = array('Session', 'RequestHandler');
  46. /**
  47. * A reference to the object used for authentication
  48. *
  49. * @var object
  50. * @link http://book.cakephp.org/view/1278/authenticate
  51. */
  52. public $authenticate = null;
  53. /**
  54. * The name of the component to use for Authorization or set this to
  55. * 'controller' will validate against Controller::isAuthorized()
  56. * 'actions' will validate Controller::action against an AclComponent::check()
  57. * 'crud' will validate mapActions against an AclComponent::check()
  58. * array('model'=> 'name'); will validate mapActions against model $name::isAuthorized(user, controller, mapAction)
  59. * 'object' will validate Controller::action against object::isAuthorized(user, controller, action)
  60. *
  61. * @var mixed
  62. * @link http://book.cakephp.org/view/1275/authorize
  63. */
  64. public $authorize = false;
  65. /**
  66. * The name of an optional view element to render when an Ajax request is made
  67. * with an invalid or expired session
  68. *
  69. * @var string
  70. * @link http://book.cakephp.org/view/1277/ajaxLogin
  71. */
  72. public $ajaxLogin = null;
  73. /**
  74. * The name of the element used for SessionComponent::setFlash
  75. *
  76. * @var string
  77. */
  78. public $flashElement = 'default';
  79. /**
  80. * The name of the model that represents users which will be authenticated. Defaults to 'User'.
  81. *
  82. * @var string
  83. * @link http://book.cakephp.org/view/1266/userModel
  84. */
  85. public $userModel = 'User';
  86. /**
  87. * Additional query conditions to use when looking up and authenticating users,
  88. * i.e. array('User.is_active' => 1).
  89. *
  90. * @var array
  91. * @link http://book.cakephp.org/view/1268/userScope
  92. */
  93. public $userScope = array();
  94. /**
  95. * Allows you to specify non-default login name and password fields used in
  96. * $userModel, i.e. array('username' => 'login_name', 'password' => 'passwd').
  97. *
  98. * @var array
  99. * @link http://book.cakephp.org/view/1267/fields
  100. */
  101. public $fields = array('username' => 'username', 'password' => 'password');
  102. /**
  103. * The session key name where the record of the current user is stored. If
  104. * unspecified, it will be "Auth.{$userModel name}".
  105. *
  106. * @var string
  107. * @link http://book.cakephp.org/view/1276/sessionKey
  108. */
  109. public $sessionKey = null;
  110. /**
  111. * If using action-based access control, this defines how the paths to action
  112. * ACO nodes is computed. If, for example, all controller nodes are nested
  113. * under an ACO node named 'Controllers', $actionPath should be set to
  114. * "Controllers/".
  115. *
  116. * @var string
  117. * @link http://book.cakephp.org/view/1279/actionPath
  118. */
  119. public $actionPath = null;
  120. /**
  121. * A URL (defined as a string or array) to the controller action that handles
  122. * logins.
  123. *
  124. * @var mixed
  125. * @link http://book.cakephp.org/view/1269/loginAction
  126. */
  127. public $loginAction = null;
  128. /**
  129. * Normally, if a user is redirected to the $loginAction page, the location they
  130. * were redirected from will be stored in the session so that they can be
  131. * redirected back after a successful login. If this session value is not
  132. * set, the user will be redirected to the page specified in $loginRedirect.
  133. *
  134. * @var mixed
  135. * @link http://book.cakephp.org/view/1270/loginRedirect
  136. */
  137. public $loginRedirect = null;
  138. /**
  139. * The default action to redirect to after the user is logged out. While AuthComponent does
  140. * not handle post-logout redirection, a redirect URL will be returned from AuthComponent::logout().
  141. * Defaults to AuthComponent::$loginAction.
  142. *
  143. * @var mixed
  144. * @see AuthComponent::$loginAction
  145. * @see AuthComponent::logout()
  146. * @link http://book.cakephp.org/view/1271/logoutRedirect
  147. */
  148. public $logoutRedirect = null;
  149. /**
  150. * The name of model or model object, or any other object has an isAuthorized method.
  151. *
  152. * @var string
  153. */
  154. public $object = null;
  155. /**
  156. * Error to display when user login fails. For security purposes, only one error is used for all
  157. * login failures, so as not to expose information on why the login failed.
  158. *
  159. * @var string
  160. * @link http://book.cakephp.org/view/1272/loginError
  161. */
  162. public $loginError = null;
  163. /**
  164. * Error to display when user attempts to access an object or action to which they do not have
  165. * acccess.
  166. *
  167. * @var string
  168. * @link http://book.cakephp.org/view/1273/authError
  169. */
  170. public $authError = null;
  171. /**
  172. * Determines whether AuthComponent will automatically redirect and exit if login is successful.
  173. *
  174. * @var boolean
  175. * @link http://book.cakephp.org/view/1274/autoRedirect
  176. */
  177. public $autoRedirect = true;
  178. /**
  179. * Controller actions for which user validation is not required.
  180. *
  181. * @var array
  182. * @see AuthComponent::allow()
  183. * @link http://book.cakephp.org/view/1251/Setting-Auth-Component-Variables
  184. */
  185. public $allowedActions = array();
  186. /**
  187. * Maps actions to CRUD operations. Used for controller-based validation ($validate = 'controller').
  188. *
  189. * @var array
  190. * @see AuthComponent::mapActions()
  191. */
  192. public $actionMap = array(
  193. 'index' => 'read',
  194. 'add' => 'create',
  195. 'edit' => 'update',
  196. 'view' => 'read',
  197. 'remove' => 'delete'
  198. );
  199. /**
  200. * Request object
  201. *
  202. * @var CakeRequest
  203. */
  204. public $request;
  205. /**
  206. * Form data from Controller::$data
  207. *
  208. * @deprecated Use $this->request->data instead
  209. * @var array
  210. */
  211. public $data = array();
  212. /**
  213. * Parameter data from Controller::$params
  214. *
  215. * @deprecated Use $this->request instead
  216. * @var array
  217. */
  218. public $params = array();
  219. /**
  220. * AclComponent instance if using Acl + Auth
  221. *
  222. * @var AclComponent
  223. */
  224. public $Acl;
  225. /**
  226. * Method list for bound controller
  227. *
  228. * @var array
  229. */
  230. protected $_methods = array();
  231. /**
  232. * Initializes AuthComponent for use in the controller
  233. *
  234. * @param object $controller A reference to the instantiating controller object
  235. * @return void
  236. */
  237. public function initialize($controller) {
  238. $this->request = $controller->request;
  239. $this->params = $this->request;
  240. $crud = array('create', 'read', 'update', 'delete');
  241. $this->actionMap = array_merge($this->actionMap, array_combine($crud, $crud));
  242. $this->_methods = $controller->methods;
  243. $prefixes = Router::prefixes();
  244. if (!empty($prefixes)) {
  245. foreach ($prefixes as $prefix) {
  246. $this->actionMap = array_merge($this->actionMap, array(
  247. $prefix . '_index' => 'read',
  248. $prefix . '_add' => 'create',
  249. $prefix . '_edit' => 'update',
  250. $prefix . '_view' => 'read',
  251. $prefix . '_remove' => 'delete',
  252. $prefix . '_create' => 'create',
  253. $prefix . '_read' => 'read',
  254. $prefix . '_update' => 'update',
  255. $prefix . '_delete' => 'delete'
  256. ));
  257. }
  258. }
  259. if (Configure::read('debug') > 0) {
  260. Debugger::checkSecurityKeys();
  261. }
  262. }
  263. /**
  264. * Main execution method. Handles redirecting of invalid users, and processing
  265. * of login form data.
  266. *
  267. * @param object $controller A reference to the instantiating controller object
  268. * @return boolean
  269. */
  270. public function startup($controller) {
  271. $isErrorOrTests = (
  272. strtolower($controller->name) == 'cakeerror' ||
  273. (strtolower($controller->name) == 'tests' && Configure::read('debug') > 0)
  274. );
  275. if ($isErrorOrTests) {
  276. return true;
  277. }
  278. $methods = array_flip($controller->methods);
  279. $action = $controller->request->params['action'];
  280. $isMissingAction = (
  281. $controller->scaffold === false &&
  282. !isset($methods[$action])
  283. );
  284. if ($isMissingAction) {
  285. return true;
  286. }
  287. if (!$this->__setDefaults()) {
  288. return false;
  289. }
  290. $request = $controller->request;
  291. $this->request->data = $controller->request->data = $this->hashPasswords($request->data);
  292. $url = '';
  293. if (isset($request->query['url'])) {
  294. $url = $request->query['url'];
  295. }
  296. $url = Router::normalize($url);
  297. $loginAction = Router::normalize($this->loginAction);
  298. $allowedActions = $this->allowedActions;
  299. $isAllowed = (
  300. $this->allowedActions == array('*') ||
  301. in_array($action, $allowedActions)
  302. );
  303. if ($loginAction != $url && $isAllowed) {
  304. return true;
  305. }
  306. if ($loginAction == $url) {
  307. $model = $this->getModel();
  308. if (empty($request->data) || !isset($request->data[$model->alias])) {
  309. if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
  310. $this->Session->write('Auth.redirect', $controller->referer(null, true));
  311. }
  312. return false;
  313. }
  314. $isValid = !empty($request->data[$model->alias][$this->fields['username']]) &&
  315. !empty($request->data[$model->alias][$this->fields['password']]);
  316. if ($isValid) {
  317. $username = $request->data[$model->alias][$this->fields['username']];
  318. $password = $request->data[$model->alias][$this->fields['password']];
  319. $data = array(
  320. $model->alias . '.' . $this->fields['username'] => $username,
  321. $model->alias . '.' . $this->fields['password'] => $password
  322. );
  323. if ($this->login($data)) {
  324. if ($this->autoRedirect) {
  325. $controller->redirect($this->redirect(), null, true);
  326. }
  327. return true;
  328. }
  329. }
  330. $this->Session->setFlash($this->loginError, $this->flashElement, array(), 'auth');
  331. $request->data[$model->alias][$this->fields['password']] = null;
  332. return false;
  333. } else {
  334. if (!$this->user()) {
  335. if (!$request->is('ajax')) {
  336. $this->Session->setFlash($this->authError, $this->flashElement, array(), 'auth');
  337. if (!empty($request->query) && count($request->query) >= 2) {
  338. $query = $request->query;
  339. unset($query['url'], $query['ext']);
  340. $url .= Router::queryString($query, array());
  341. }
  342. $this->Session->write('Auth.redirect', $url);
  343. $controller->redirect($loginAction);
  344. return false;
  345. } elseif (!empty($this->ajaxLogin)) {
  346. $controller->viewPath = 'elements';
  347. echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
  348. $this->_stop();
  349. return false;
  350. } else {
  351. $controller->redirect(null, 403);
  352. }
  353. }
  354. }
  355. if (!$this->authorize) {
  356. return true;
  357. }
  358. extract($this->__authType());
  359. switch ($type) {
  360. case 'controller':
  361. $this->object = $controller;
  362. break;
  363. case 'crud':
  364. case 'actions':
  365. if (isset($controller->Acl)) {
  366. $this->Acl = $controller->Acl;
  367. } else {
  368. trigger_error(__('Could not find AclComponent. Please include Acl in Controller::$components.'), E_USER_WARNING);
  369. }
  370. break;
  371. case 'model':
  372. if (!isset($object)) {
  373. $hasModel = (
  374. isset($controller->{$controller->modelClass}) &&
  375. is_object($controller->{$controller->modelClass})
  376. );
  377. $isUses = (
  378. !empty($controller->uses) && isset($controller->{$controller->uses[0]}) &&
  379. is_object($controller->{$controller->uses[0]})
  380. );
  381. if ($hasModel) {
  382. $object = $controller->modelClass;
  383. } elseif ($isUses) {
  384. $object = $controller->uses[0];
  385. }
  386. }
  387. $type = array('model' => $object);
  388. break;
  389. }
  390. if ($this->isAuthorized($type)) {
  391. return true;
  392. }
  393. $this->Session->setFlash($this->authError, $this->flashElement, array(), 'auth');
  394. $controller->redirect($controller->referer(), null, true);
  395. return false;
  396. }
  397. /**
  398. * Attempts to introspect the correct values for object properties including
  399. * $userModel and $sessionKey.
  400. *
  401. * @param object $controller A reference to the instantiating controller object
  402. * @return boolean
  403. * @access private
  404. */
  405. function __setDefaults() {
  406. if (empty($this->userModel)) {
  407. trigger_error(__("Could not find \$userModel. Please set AuthComponent::\$userModel in beforeFilter()."), E_USER_WARNING);
  408. return false;
  409. }
  410. list($plugin, $model) = pluginSplit($this->userModel);
  411. $defaults = array(
  412. 'loginAction' => array(
  413. 'controller' => Inflector::underscore(Inflector::pluralize($model)),
  414. 'action' => 'login',
  415. 'plugin' => Inflector::underscore($plugin),
  416. ),
  417. 'sessionKey' => 'Auth.' . $model,
  418. 'logoutRedirect' => $this->loginAction,
  419. 'loginError' => __('Login failed. Invalid username or password.'),
  420. 'authError' => __('You are not authorized to access that location.')
  421. );
  422. foreach ($defaults as $key => $value) {
  423. if (empty($this->{$key})) {
  424. $this->{$key} = $value;
  425. }
  426. }
  427. return true;
  428. }
  429. /**
  430. * Determines whether the given user is authorized to perform an action. The type of
  431. * authorization used is based on the value of AuthComponent::$authorize or the
  432. * passed $type param.
  433. *
  434. * Types:
  435. * 'controller' will validate against Controller::isAuthorized() if controller instance is
  436. * passed in $object
  437. * 'actions' will validate Controller::action against an AclComponent::check()
  438. * 'crud' will validate mapActions against an AclComponent::check()
  439. * array('model'=> 'name'); will validate mapActions against model
  440. * $name::isAuthorized(user, controller, mapAction)
  441. * 'object' will validate Controller::action against
  442. * object::isAuthorized(user, controller, action)
  443. *
  444. * @param string $type Type of authorization
  445. * @param mixed $object object, model object, or model name
  446. * @param mixed $user The user to check the authorization of
  447. * @return boolean True if $user is authorized, otherwise false
  448. */
  449. public function isAuthorized($type = null, $object = null, $user = null) {
  450. if (empty($user) && !$this->user()) {
  451. return false;
  452. } elseif (empty($user)) {
  453. $user = $this->user();
  454. }
  455. extract($this->__authType($type));
  456. if (!$object) {
  457. $object = $this->object;
  458. }
  459. $valid = false;
  460. switch ($type) {
  461. case 'controller':
  462. $valid = $object->isAuthorized();
  463. break;
  464. case 'actions':
  465. $valid = $this->Acl->check($user, $this->action());
  466. break;
  467. case 'crud':
  468. if (!isset($this->actionMap[$this->request['action']])) {
  469. trigger_error(
  470. __('Auth::startup() - Attempted access of un-mapped action "%1$s" in controller "%2$s"', $this->request['action'], $this->request['controller']),
  471. E_USER_WARNING
  472. );
  473. } else {
  474. $valid = $this->Acl->check(
  475. $user,
  476. $this->action(':controller'),
  477. $this->actionMap[$this->request['action']]
  478. );
  479. }
  480. break;
  481. case 'model':
  482. $action = $this->request['action'];
  483. if (isset($this->actionMap[$action])) {
  484. $action = $this->actionMap[$action];
  485. }
  486. if (is_string($object)) {
  487. $object = $this->getModel($object);
  488. }
  489. case 'object':
  490. if (!isset($action)) {
  491. $action = $this->action(':action');
  492. }
  493. if (empty($object)) {
  494. trigger_error(__('Could not find %s. Set AuthComponent::$object in beforeFilter() or pass a valid object', get_class($object)), E_USER_WARNING);
  495. return;
  496. }
  497. if (method_exists($object, 'isAuthorized')) {
  498. $valid = $object->isAuthorized($user, $this->action(':controller'), $action);
  499. } elseif ($object) {
  500. trigger_error(__('%s::isAuthorized() is not defined.', get_class($object)), E_USER_WARNING);
  501. }
  502. break;
  503. case null:
  504. case false:
  505. return true;
  506. break;
  507. default:
  508. trigger_error(__('Auth::isAuthorized() - $authorize is set to an incorrect value. Allowed settings are: "actions", "crud", "model" or null.'), E_USER_WARNING);
  509. break;
  510. }
  511. return $valid;
  512. }
  513. /**
  514. * Get authorization type
  515. *
  516. * @param string $auth Type of authorization
  517. * @return array Associative array with: type, object
  518. * @access private
  519. */
  520. function __authType($auth = null) {
  521. if ($auth == null) {
  522. $auth = $this->authorize;
  523. }
  524. $object = null;
  525. if (is_array($auth)) {
  526. $type = key($auth);
  527. $object = $auth[$type];
  528. } else {
  529. $type = $auth;
  530. return compact('type');
  531. }
  532. return compact('type', 'object');
  533. }
  534. /**
  535. * Takes a list of actions in the current controller for which authentication is not required, or
  536. * no parameters to allow all actions.
  537. *
  538. * @param mixed $action Controller action name or array of actions
  539. * @param string $action Controller action name
  540. * @param string ... etc.
  541. * @return void
  542. * @link http://book.cakephp.org/view/1257/allow
  543. */
  544. public function allow() {
  545. $args = func_get_args();
  546. if (empty($args) || $args == array('*')) {
  547. $this->allowedActions = $this->_methods;
  548. } else {
  549. if (isset($args[0]) && is_array($args[0])) {
  550. $args = $args[0];
  551. }
  552. $this->allowedActions = array_merge($this->allowedActions, $args);
  553. }
  554. }
  555. /**
  556. * Removes items from the list of allowed actions.
  557. *
  558. * @param mixed $action Controller action name or array of actions
  559. * @param string $action Controller action name
  560. * @param string ... etc.
  561. * @return void
  562. * @see AuthComponent::allow()
  563. * @link http://book.cakephp.org/view/1258/deny
  564. */
  565. public function deny() {
  566. $args = func_get_args();
  567. if (isset($args[0]) && is_array($args[0])) {
  568. $args = $args[0];
  569. }
  570. foreach ($args as $arg) {
  571. $i = array_search($arg, $this->allowedActions);
  572. if (is_int($i)) {
  573. unset($this->allowedActions[$i]);
  574. }
  575. }
  576. $this->allowedActions = array_values($this->allowedActions);
  577. }
  578. /**
  579. * Maps action names to CRUD operations. Used for controller-based authentication.
  580. *
  581. * @param array $map Actions to map
  582. * @return void
  583. * @link http://book.cakephp.org/view/1260/mapActions
  584. */
  585. public function mapActions($map = array()) {
  586. $crud = array('create', 'read', 'update', 'delete');
  587. foreach ($map as $action => $type) {
  588. if (in_array($action, $crud) && is_array($type)) {
  589. foreach ($type as $typedAction) {
  590. $this->actionMap[$typedAction] = $action;
  591. }
  592. } else {
  593. $this->actionMap[$action] = $type;
  594. }
  595. }
  596. }
  597. /**
  598. * Manually log-in a user with the given parameter data. The $data provided can be any data
  599. * structure used to identify a user in AuthComponent::identify(). If $data is empty or not
  600. * specified, POST data from Controller::$data will be used automatically.
  601. *
  602. * After (if) login is successful, the user record is written to the session key specified in
  603. * AuthComponent::$sessionKey.
  604. *
  605. * @param mixed $data User object
  606. * @return boolean True on login success, false on failure
  607. * @link http://book.cakephp.org/view/1261/login
  608. */
  609. public function login($data = null) {
  610. $this->__setDefaults();
  611. $this->_loggedIn = false;
  612. if (empty($data)) {
  613. $data = $this->data;
  614. }
  615. if ($user = $this->identify($data)) {
  616. $this->Session->write($this->sessionKey, $user);
  617. $this->_loggedIn = true;
  618. }
  619. return $this->_loggedIn;
  620. }
  621. /**
  622. * Logs a user out, and returns the login action to redirect to.
  623. *
  624. * @param mixed $url Optional URL to redirect the user to after logout
  625. * @return string AuthComponent::$loginAction
  626. * @see AuthComponent::$loginAction
  627. * @link http://book.cakephp.org/view/1262/logout
  628. */
  629. public function logout() {
  630. $this->__setDefaults();
  631. $this->Session->delete($this->sessionKey);
  632. $this->Session->delete('Auth.redirect');
  633. $this->_loggedIn = false;
  634. return Router::normalize($this->logoutRedirect);
  635. }
  636. /**
  637. * Get the current user from the session.
  638. *
  639. * @param string $key field to retrive. Leave null to get entire User record
  640. * @return mixed User record. or null if no user is logged in.
  641. * @link http://book.cakephp.org/view/1264/user
  642. */
  643. public function user($key = null) {
  644. $this->__setDefaults();
  645. if (!$this->Session->check($this->sessionKey)) {
  646. return null;
  647. }
  648. if ($key == null) {
  649. $model = $this->getModel();
  650. return array($model->alias => $this->Session->read($this->sessionKey));
  651. } else {
  652. $user = $this->Session->read($this->sessionKey);
  653. if (isset($user[$key])) {
  654. return $user[$key];
  655. }
  656. return null;
  657. }
  658. }
  659. /**
  660. * If no parameter is passed, gets the authentication redirect URL.
  661. *
  662. * @param mixed $url Optional URL to write as the login redirect URL.
  663. * @return string Redirect URL
  664. */
  665. public function redirect($url = null) {
  666. if (!is_null($url)) {
  667. $redir = $url;
  668. $this->Session->write('Auth.redirect', $redir);
  669. } elseif ($this->Session->check('Auth.redirect')) {
  670. $redir = $this->Session->read('Auth.redirect');
  671. $this->Session->delete('Auth.redirect');
  672. if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
  673. $redir = $this->loginRedirect;
  674. }
  675. } else {
  676. $redir = $this->loginRedirect;
  677. }
  678. return Router::normalize($redir);
  679. }
  680. /**
  681. * Validates a user against an abstract object.
  682. *
  683. * @param mixed $object The object to validate the user against.
  684. * @param mixed $user Optional. The identity of the user to be validated.
  685. * Uses the current user session if none specified. For
  686. * valid forms of identifying users, see
  687. * AuthComponent::identify().
  688. * @param string $action Optional. The action to validate against.
  689. * @see AuthComponent::identify()
  690. * @return boolean True if the user validates, false otherwise.
  691. */
  692. public function validate($object, $user = null, $action = null) {
  693. if (empty($user)) {
  694. $user = $this->user();
  695. }
  696. if (empty($user)) {
  697. return false;
  698. }
  699. return $this->Acl->check($user, $object, $action);
  700. }
  701. /**
  702. * Returns the path to the ACO node bound to a controller/action.
  703. *
  704. * @param string $action Optional. The controller/action path to validate the
  705. * user against. The current request action is used if
  706. * none is specified.
  707. * @return boolean ACO node path
  708. * @link http://book.cakephp.org/view/1256/action
  709. */
  710. public function action($action = ':plugin/:controller/:action') {
  711. $plugin = empty($this->request['plugin']) ? null : Inflector::camelize($this->request['plugin']) . '/';
  712. return str_replace(
  713. array(':controller', ':action', ':plugin/'),
  714. array(Inflector::camelize($this->request['controller']), $this->request['action'], $plugin),
  715. $this->actionPath . $action
  716. );
  717. }
  718. /**
  719. * Returns a reference to the model object specified, and attempts
  720. * to load it if it is not found.
  721. *
  722. * @param string $name Model name (defaults to AuthComponent::$userModel)
  723. * @return object A reference to a model object
  724. */
  725. public function &getModel($name = null) {
  726. $model = null;
  727. if (!$name) {
  728. $name = $this->userModel;
  729. }
  730. $model = ClassRegistry::init($name);
  731. if (empty($model)) {
  732. trigger_error(__('Auth::getModel() - Model is not set or could not be found'), E_USER_WARNING);
  733. return null;
  734. }
  735. return $model;
  736. }
  737. /**
  738. * Identifies a user based on specific criteria.
  739. *
  740. * @param mixed $user Optional. The identity of the user to be validated.
  741. * Uses the current user session if none specified.
  742. * @param array $conditions Optional. Additional conditions to a find.
  743. * @return array User record data, or null, if the user could not be identified.
  744. */
  745. public function identify($user = null, $conditions = null) {
  746. if ($conditions === false) {
  747. $conditions = null;
  748. } elseif (is_array($conditions)) {
  749. $conditions = array_merge((array)$this->userScope, $conditions);
  750. } else {
  751. $conditions = $this->userScope;
  752. }
  753. $model = $this->getModel();
  754. if (empty($user)) {
  755. $user = $this->user();
  756. if (empty($user)) {
  757. return null;
  758. }
  759. } elseif (is_object($user) && is_a($user, 'Model')) {
  760. if (!$user->exists()) {
  761. return null;
  762. }
  763. $user = $user->read();
  764. $user = $user[$model->alias];
  765. } elseif (is_array($user) && isset($user[$model->alias])) {
  766. $user = $user[$model->alias];
  767. }
  768. if (is_array($user) && (isset($user[$this->fields['username']]) || isset($user[$model->alias . '.' . $this->fields['username']]))) {
  769. if (isset($user[$this->fields['username']]) && !empty($user[$this->fields['username']]) && !empty($user[$this->fields['password']])) {
  770. if (trim($user[$this->fields['username']]) == '=' || trim($user[$this->fields['password']]) == '=') {
  771. return false;
  772. }
  773. $find = array(
  774. $model->alias.'.'.$this->fields['username'] => $user[$this->fields['username']],
  775. $model->alias.'.'.$this->fields['password'] => $user[$this->fields['password']]
  776. );
  777. } elseif (isset($user[$model->alias . '.' . $this->fields['username']]) && !empty($user[$model->alias . '.' . $this->fields['username']])) {
  778. if (trim($user[$model->alias . '.' . $this->fields['username']]) == '=' || trim($user[$model->alias . '.' . $this->fields['password']]) == '=') {
  779. return false;
  780. }
  781. $find = array(
  782. $model->alias.'.'.$this->fields['username'] => $user[$model->alias . '.' . $this->fields['username']],
  783. $model->alias.'.'.$this->fields['password'] => $user[$model->alias . '.' . $this->fields['password']]
  784. );
  785. } else {
  786. return false;
  787. }
  788. $data = $model->find('first', array(
  789. 'conditions' => array_merge($find, $conditions),
  790. 'recursive' => 0
  791. ));
  792. if (empty($data) || empty($data[$model->alias])) {
  793. return null;
  794. }
  795. } elseif (!empty($user) && is_string($user)) {
  796. $data = $model->find('first', array(
  797. 'conditions' => array_merge(array($model->escapeField() => $user), $conditions),
  798. ));
  799. if (empty($data) || empty($data[$model->alias])) {
  800. return null;
  801. }
  802. }
  803. if (!empty($data)) {
  804. if (!empty($data[$model->alias][$this->fields['password']])) {
  805. unset($data[$model->alias][$this->fields['password']]);
  806. }
  807. return $data[$model->alias];
  808. }
  809. return null;
  810. }
  811. /**
  812. * Hash any passwords found in $data using $userModel and $fields['password']
  813. *
  814. * @param array $data Set of data to look for passwords
  815. * @return array Data with passwords hashed
  816. * @link http://book.cakephp.org/view/1259/hashPasswords
  817. */
  818. public function hashPasswords($data) {
  819. if (is_object($this->authenticate) && method_exists($this->authenticate, 'hashPasswords')) {
  820. return $this->authenticate->hashPasswords($data);
  821. }
  822. if (is_array($data)) {
  823. $model = $this->getModel();
  824. if(isset($data[$model->alias])) {
  825. if (isset($data[$model->alias][$this->fields['username']]) && isset($data[$model->alias][$this->fields['password']])) {
  826. $data[$model->alias][$this->fields['password']] = $this->password($data[$model->alias][$this->fields['password']]);
  827. }
  828. }
  829. }
  830. return $data;
  831. }
  832. /**
  833. * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
  834. *
  835. * @param string $password Password to hash
  836. * @return string Hashed password
  837. * @link http://book.cakephp.org/view/1263/password
  838. */
  839. public function password($password) {
  840. return Security::hash($password, null, true);
  841. }
  842. /**
  843. * Component shutdown. If user is logged in, wipe out redirect.
  844. *
  845. * @param object $controller Instantiating controller
  846. */
  847. public function shutdown($controller) {
  848. if ($this->_loggedIn) {
  849. $this->Session->delete('Auth.redirect');
  850. }
  851. }
  852. /**
  853. * Sets or gets whether the user is logged in
  854. *
  855. * @param boolean $logged sets the status of the user, true to logged in, false to logged out
  856. * @return boolean true if the user is logged in, false otherwise
  857. * @access public
  858. */
  859. public function loggedIn($logged = null) {
  860. if (!is_null($logged)) {
  861. $this->_loggedIn = $logged;
  862. }
  863. return $this->_loggedIn;
  864. }
  865. }