PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/code/ryzom/tools/server/www/webtt/cake/libs/controller/components/auth.php

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