cake/libs/controller/components/auth.php

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