PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/controller/components/auth.php

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