CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 1.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 1.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Classes

  • AclBase
  • AclBehavior
  • AclComponent
  • AclNode
  • AclShell
  • Aco
  • AcoAction
  • AjaxHelper
  • ApcEngine
  • ApiShell
  • App
  • AppController
  • AppHelper
  • AppModel
  • Aro
  • AuthComponent
  • BakeShell
  • BehaviorCollection
  • Cache
  • CacheEngine
  • CacheHelper
  • CakeErrorController
  • CakeLog
  • CakeSchema
  • CakeSession
  • CakeSocket
  • ClassRegistry
  • Component
  • Configure
  • ConnectionManager
  • ConsoleShell
  • ContainableBehavior
  • Controller
  • ControllerTask
  • CookieComponent
  • DataSource
  • DbAcl
  • DbAclSchema
  • DbConfigTask
  • DboAdodb
  • DboDb2
  • DboFirebird
  • DboMssql
  • DboMysql
  • DboMysqlBase
  • DboMysqli
  • DboOdbc
  • DboOracle
  • DboPostgres
  • DboSource
  • DboSqlite
  • DboSybase
  • Debugger
  • EmailComponent
  • ErrorHandler
  • ExtractTask
  • File
  • FileEngine
  • Flay
  • Folder
  • FormHelper
  • Helper
  • HtmlHelper
  • HttpSocket
  • I18n
  • I18nModel
  • i18nSchema
  • I18nShell
  • Inflector
  • IniAcl
  • JavascriptHelper
  • JsHelper
  • JsHelperObject
  • L10n
  • MagicDb
  • MagicFileResource
  • MediaView
  • MemcacheEngine
  • Model
  • ModelBehavior
  • ModelTask
  • Multibyte
  • NumberHelper
  • Object
  • Overloadable
  • Overloadable2
  • PagesController
  • PaginatorHelper
  • Permission
  • PluginTask
  • ProjectTask
  • RequestHandlerComponent
  • Router
  • RssHelper
  • Sanitize
  • Scaffold
  • ScaffoldView
  • SchemaShell
  • Security
  • SecurityComponent
  • SessionComponent
  • SessionHelper
  • SessionsSchema
  • Set
  • Shell
  • String
  • TestSuiteShell
  • TestTask
  • TextHelper
  • ThemeView
  • TimeHelper
  • TranslateBehavior
  • TreeBehavior
  • Validation
  • View
  • ViewTask
  • XcacheEngine
  • Xml
  • XmlElement
  • XmlHelper
  • XmlManager
  • XmlNode
  • XmlTextNode

Functions

  • __enclose
  • make_clean_css
  • mb_encode_mimeheader
  • mb_stripos
  • mb_stristr
  • mb_strlen
  • mb_strpos
  • mb_strrchr
  • mb_strrichr
  • mb_strripos
  • mb_strrpos
  • mb_strstr
  • mb_strtolower
  • mb_strtoupper
  • mb_substr
  • mb_substr_count
  • write_css_cache
  1: <?php
  2: /* SVN FILE: $Id$ */
  3: 
  4: /**
  5:  * Authentication component
  6:  *
  7:  * Manages user logins and permissions.
  8:  *
  9:  * PHP versions 4 and 5
 10:  *
 11:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 12:  * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 13:  *
 14:  * Licensed under The MIT License
 15:  * Redistributions of files must retain the above copyright notice.
 16:  *
 17:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 18:  * @link          http://cakephp.org CakePHP(tm) Project
 19:  * @package       cake
 20:  * @subpackage    cake.cake.libs.controller.components
 21:  * @since         CakePHP(tm) v 0.10.0.1076
 22:  * @version       $Revision$
 23:  * @modifiedby    $LastChangedBy$
 24:  * @lastmodified  $Date$
 25:  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 26:  */
 27: 
 28: App::import(array('Router', 'Security'));
 29: 
 30: /**
 31:  * Authentication control component class
 32:  *
 33:  * Binds access control with user authentication and session management.
 34:  *
 35:  * @package       cake
 36:  * @subpackage    cake.cake.libs.controller.components
 37:  */
 38: class AuthComponent extends Object {
 39: /**
 40:  * Maintains current user login state.
 41:  *
 42:  * @var boolean
 43:  * @access private
 44:  */
 45:     var $_loggedIn = false;
 46: /**
 47:  * Other components utilized by AuthComponent
 48:  *
 49:  * @var array
 50:  * @access public
 51:  */
 52:     var $components = array('Session', 'RequestHandler');
 53: /**
 54:  * A reference to the object used for authentication
 55:  *
 56:  * @var object
 57:  * @access public
 58:  */
 59:     var $authenticate = null;
 60: /**
 61:  * The name of the component to use for Authorization or set this to
 62:  * 'controller' will validate against Controller::isAuthorized()
 63:  * 'actions' will validate Controller::action against an AclComponent::check()
 64:  * 'crud' will validate mapActions against an AclComponent::check()
 65:  * array('model'=> 'name'); will validate mapActions against model $name::isAuthorized(user, controller, mapAction)
 66:  * 'object' will validate Controller::action against object::isAuthorized(user, controller, action)
 67:  *
 68:  * @var mixed
 69:  * @access public
 70:  */
 71:     var $authorize = false;
 72: /**
 73:  * The name of an optional view element to render when an Ajax request is made
 74:  * with an invalid or expired session
 75:  *
 76:  * @var string
 77:  * @access public
 78:  */
 79:     var $ajaxLogin = null;
 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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $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:     var $data = array();
209: /**
210:  * Parameter data from Controller::$params
211:  *
212:  * @var array
213:  * @access public
214:  */
215:     var $params = array();
216: /**
217:  * Method list for bound controller
218:  *
219:  * @var array
220:  * @access protected
221:  */
222:     var $_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:     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: 
236:         $admin = Configure::read('Routing.admin');
237:         if (!empty($admin)) {
238:             $this->actionMap = array_merge($this->actionMap, array(
239:                 $admin . '_index'   => 'read',
240:                 $admin . '_add'     => 'create',
241:                 $admin . '_edit'    => 'update',
242:                 $admin . '_view'    => 'read',
243:                 $admin . '_remove'  => 'delete',
244:                 $admin . '_create'  => 'create',
245:                 $admin . '_read'    => 'read',
246:                 $admin . '_update'  => 'update',
247:                 $admin . '_delete'  => 'delete'
248:             ));
249:         }
250:         if (Configure::read() > 0) {
251:             App::import('Debugger');
252:             Debugger::checkSessionKey();
253:         }
254:     }
255: /**
256:  * Main execution method.  Handles redirecting of invalid users, and processing
257:  * of login form data.
258:  *
259:  * @param object $controller A reference to the instantiating controller object
260:  * @return boolean
261:  * @access public
262:  */
263:     function startup(&$controller) {
264:         $isErrorOrTests = (
265:             strtolower($controller->name) == 'cakeerror' ||
266:             (strtolower($controller->name) == 'tests' && Configure::read() > 0)
267:         );
268:         if ($isErrorOrTests) {
269:             return true;
270:         }
271: 
272:         $methods = array_flip($controller->methods);
273:         $action = strtolower($controller->params['action']);
274:         $isMissingAction = (
275:             $controller->scaffold === false &&
276:             !isset($methods[$action])
277:         );
278: 
279:         if ($isMissingAction) {
280:             return true;
281:         }
282: 
283:         if (!$this->__setDefaults()) {
284:             return false;
285:         }
286: 
287:         $this->data = $controller->data = $this->hashPasswords($controller->data);
288:         $url = '';
289: 
290:         if (isset($controller->params['url']['url'])) {
291:             $url = $controller->params['url']['url'];
292:         }
293:         $url = Router::normalize($url);
294:         $loginAction = Router::normalize($this->loginAction);
295: 
296:         $allowedActions = array_map('strtolower', $this->allowedActions);
297:         $isAllowed = (
298:             $this->allowedActions == array('*') ||
299:             in_array($action, $allowedActions)
300:         );
301: 
302:         if ($loginAction != $url && $isAllowed) {
303:             return true;
304:         }
305: 
306:         if ($loginAction == $url) {
307:             if (empty($controller->data) || !isset($controller->data[$this->userModel])) {
308:                 if (!$this->Session->check('Auth.redirect') && env('HTTP_REFERER')) {
309:                     $this->Session->write('Auth.redirect', $controller->referer(null, true));
310:                 }
311:                 return false;
312:             }
313: 
314:             $isValid = !empty($controller->data[$this->userModel][$this->fields['username']]) &&
315:                 !empty($controller->data[$this->userModel][$this->fields['password']]);
316: 
317:             if ($isValid) {
318:                 $username = $controller->data[$this->userModel][$this->fields['username']];
319:                 $password = $controller->data[$this->userModel][$this->fields['password']];
320: 
321:                 $data = array(
322:                     $this->userModel . '.' . $this->fields['username'] => $username,
323:                     $this->userModel . '.' . $this->fields['password'] => $password
324:                 );
325: 
326:                 if ($this->login($data)) {
327:                     if ($this->autoRedirect) {
328:                         $controller->redirect($this->redirect(), null, true);
329:                     }
330:                     return true;
331:                 }
332:             }
333: 
334:             $this->Session->setFlash($this->loginError, 'default', array(), 'auth');
335:             $controller->data[$this->userModel][$this->fields['password']] = null;
336:             return false;
337:         } else {
338:             if (!$this->user()) {
339:                 if (!$this->RequestHandler->isAjax()) {
340:                     $this->Session->setFlash($this->authError, 'default', array(), 'auth');
341:                     if (!empty($controller->params['url']) && count($controller->params['url']) >= 2) {
342:                         $query = $controller->params['url'];
343:                         unset($query['url'], $query['ext']);
344:                         $url .= Router::queryString($query, array());
345:                     }
346:                     $this->Session->write('Auth.redirect', $url);
347:                     $controller->redirect($loginAction);
348:                     return false;
349:                 } elseif (!empty($this->ajaxLogin)) {
350:                     $controller->viewPath = 'elements';
351:                     echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
352:                     $this->_stop();
353:                     return false;
354:                 } else {
355:                     $controller->redirect(null, 403);
356:                 }
357:             }
358:         }
359: 
360:         if (!$this->authorize) {
361:             return true;
362:         }
363: 
364:         extract($this->__authType());
365:         switch ($type) {
366:             case 'controller':
367:                 $this->object =& $controller;
368:             break;
369:             case 'crud':
370:             case 'actions':
371:                 if (isset($controller->Acl)) {
372:                     $this->Acl =& $controller->Acl;
373:                 } else {
374:                     $err = 'Could not find AclComponent. Please include Acl in ';
375:                     $err .= 'Controller::$components.';
376:                     trigger_error(__($err, true), E_USER_WARNING);
377:                 }
378:             break;
379:             case 'model':
380:                 if (!isset($object)) {
381:                     $hasModel = (
382:                         isset($controller->{$controller->modelClass}) &&
383:                         is_object($controller->{$controller->modelClass})
384:                     );
385:                     $isUses = (
386:                         !empty($controller->uses) && isset($controller->{$controller->uses[0]}) &&
387:                         is_object($controller->{$controller->uses[0]})
388:                     );
389: 
390:                     if ($hasModel) {
391:                         $object = $controller->modelClass;
392:                     } elseif ($isUses) {
393:                         $object = $controller->uses[0];
394:                     }
395:                 }
396:                 $type = array('model' => $object);
397:             break;
398:         }
399: 
400:         if ($this->isAuthorized($type)) {
401:             return true;
402:         }
403: 
404:         $this->Session->setFlash($this->authError, 'default', 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:         $defaults = array(
422:             'loginAction' => array(
423:                 'controller' => Inflector::underscore(Inflector::pluralize($this->userModel)),
424:                 'action' => 'login'
425:             ),
426:             'sessionKey' => 'Auth.' . $this->userModel,
427:             'logoutRedirect' => $this->loginAction,
428:             'loginError' => __('Login failed. Invalid username or password.', true),
429:             'authError' => __('You are not authorized to access that location.', true)
430:         );
431:         foreach ($defaults as $key => $value) {
432:             if (empty($this->{$key})) {
433:                 $this->{$key} = $value;
434:             }
435:         }
436:         return true;
437:     }
438: /**
439:  * Determines whether the given user is authorized to perform an action.  The type of
440:  * authorization used is based on the value of AuthComponent::$authorize or the
441:  * passed $type param.
442:  *
443:  * Types:
444:  * 'controller' will validate against Controller::isAuthorized() if controller instance is
445:  *              passed in $object
446:  * 'actions' will validate Controller::action against an AclComponent::check()
447:  * 'crud' will validate mapActions against an AclComponent::check()
448:  *      array('model'=> 'name'); will validate mapActions against model
449:  *      $name::isAuthorized(user, controller, mapAction)
450:  * 'object' will validate Controller::action against
451:  *      object::isAuthorized(user, controller, action)
452:  *
453:  * @param string $type Type of authorization
454:  * @param mixed $object object, model object, or model name
455:  * @param mixed $user The user to check the authorization of
456:  * @return boolean True if $user is authorized, otherwise false
457:  * @access public
458:  */
459:     function isAuthorized($type = null, $object = null, $user = null) {
460:         if (empty($user) && !$this->user()) {
461:             return false;
462:         } elseif (empty($user)) {
463:             $user = $this->user();
464:         }
465: 
466:         extract($this->__authType($type));
467: 
468:         if (!$object) {
469:             $object = $this->object;
470:         }
471: 
472:         $valid = false;
473:         switch ($type) {
474:             case 'controller':
475:                 $valid = $object->isAuthorized();
476:             break;
477:             case 'actions':
478:                 $valid = $this->Acl->check($user, $this->action());
479:             break;
480:             case 'crud':
481:                 $this->mapActions();
482:                 if (!isset($this->actionMap[$this->params['action']])) {
483:                     $err = 'Auth::startup() - Attempted access of un-mapped action "%1$s" in';
484:                     $err .= ' controller "%2$s"';
485:                     trigger_error(
486:                         sprintf(__($err, true), $this->params['action'], $this->params['controller']),
487:                         E_USER_WARNING
488:                     );
489:                 } else {
490:                     $valid = $this->Acl->check(
491:                         $user,
492:                         $this->action(':controller'),
493:                         $this->actionMap[$this->params['action']]
494:                     );
495:                 }
496:             break;
497:             case 'model':
498:                 $this->mapActions();
499:                 $action = $this->params['action'];
500:                 if (isset($this->actionMap[$action])) {
501:                     $action = $this->actionMap[$action];
502:                 }
503:                 if (is_string($object)) {
504:                     $object = $this->getModel($object);
505:                 }
506:             case 'object':
507:                 if (!isset($action)) {
508:                     $action = $this->action(':action');
509:                 }
510:                 if (empty($object)) {
511:                     trigger_error(sprintf(__('Could not find %s. Set AuthComponent::$object in beforeFilter() or pass a valid object', true), get_class($object)), E_USER_WARNING);
512:                     return;
513:                 }
514:                 if (method_exists($object, 'isAuthorized')) {
515:                     $valid = $object->isAuthorized($user, $this->action(':controller'), $action);
516:                 } elseif ($object) {
517:                     trigger_error(sprintf(__('%s::isAuthorized() is not defined.', true), get_class($object)), E_USER_WARNING);
518:                 }
519:             break;
520:             case null:
521:             case false:
522:                 return true;
523:             break;
524:             default:
525:                 trigger_error(__('Auth::isAuthorized() - $authorize is set to an incorrect value.  Allowed settings are: "actions", "crud", "model" or null.', true), E_USER_WARNING);
526:             break;
527:         }
528:         return $valid;
529:     }
530: /**
531:  * Get authorization type
532:  *
533:  * @param string $auth Type of authorization
534:  * @return array Associative array with: type, object
535:  * @access private
536:  */
537:     function __authType($auth = null) {
538:         if ($auth == null) {
539:             $auth = $this->authorize;
540:         }
541:         $object = null;
542:         if (is_array($auth)) {
543:             $type = key($auth);
544:             $object = $auth[$type];
545:         } else {
546:             $type = $auth;
547:             return compact('type');
548:         }
549:         return compact('type', 'object');
550:     }
551: /**
552:  * Takes a list of actions in the current controller for which authentication is not required, or
553:  * no parameters to allow all actions.
554:  *
555:  * @param string $action Controller action name
556:  * @param string $action Controller action name
557:  * @param string ... etc.
558:  * @return void
559:  * @access public
560:  */
561:     function allow() {
562:         $args = func_get_args();
563:         if (empty($args) || $args == array('*')) {
564:             $this->allowedActions = $this->_methods;
565:         } else {
566:             if (isset($args[0]) && is_array($args[0])) {
567:                 $args = $args[0];
568:             }
569:             $this->allowedActions = array_merge($this->allowedActions, $args);
570:         }
571:     }
572: /**
573:  * Removes items from the list of allowed actions.
574:  *
575:  * @param string $action Controller action name
576:  * @param string $action Controller action name
577:  * @param string ... etc.
578:  * @return void
579:  * @see AuthComponent::allow()
580:  * @access public
581:  */
582:     function deny() {
583:         $args = func_get_args();
584:         foreach ($args as $arg) {
585:             $i = array_search($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:  */
599:     function mapActions($map = array()) {
600:         $crud = array('create', 'read', 'update', 'delete');
601:         foreach ($map as $action => $type) {
602:             if (in_array($action, $crud) && is_array($type)) {
603:                 foreach ($type as $typedAction) {
604:                     $this->actionMap[$typedAction] = $action;
605:                 }
606:             } else {
607:                 $this->actionMap[$action] = $type;
608:             }
609:         }
610:     }
611: /**
612:  * Manually log-in a user with the given parameter data.  The $data provided can be any data
613:  * structure used to identify a user in AuthComponent::identify().  If $data is empty or not
614:  * specified, POST data from Controller::$data will be used automatically.
615:  *
616:  * After (if) login is successful, the user record is written to the session key specified in
617:  * AuthComponent::$sessionKey.
618:  *
619:  * @param mixed $data User object
620:  * @return boolean True on login success, false on failure
621:  * @access public
622:  */
623:     function login($data = null) {
624:         $this->__setDefaults();
625:         $this->_loggedIn = false;
626: 
627:         if (empty($data)) {
628:             $data = $this->data;
629:         }
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:  */
645:     function logout() {
646:         $this->__setDefaults();
647:         $this->Session->del($this->sessionKey);
648:         $this->Session->del('Auth.redirect');
649:         $this->_loggedIn = false;
650:         return Router::normalize($this->logoutRedirect);
651:     }
652: /**
653:  * Get the current user from the session.
654:  *
655:  * @param string $key field to retrive.  Leave null to get entire User record
656:  * @return mixed User record. or null if no user is logged in.
657:  * @access public
658:  */
659:     function user($key = null) {
660:         $this->__setDefaults();
661:         if (!$this->Session->check($this->sessionKey)) {
662:             return null;
663:         }
664: 
665:         if ($key == null) {
666:             return array($this->userModel => $this->Session->read($this->sessionKey));
667:         } else {
668:             $user = $this->Session->read($this->sessionKey);
669:             if (isset($user[$key])) {
670:                 return $user[$key];
671:             }
672:             return null;
673:         }
674:     }
675: /**
676:  * If no parameter is passed, gets the authentication redirect URL.
677:  *
678:  * @param mixed $url Optional URL to write as the login redirect URL.
679:  * @return string Redirect URL
680:  * @access public
681:  */
682:     function redirect($url = null) {
683:         if (!is_null($url)) {
684:             $redir = $url;
685:             $this->Session->write('Auth.redirect', $redir);
686:         } elseif ($this->Session->check('Auth.redirect')) {
687:             $redir = $this->Session->read('Auth.redirect');
688:             $this->Session->delete('Auth.redirect');
689: 
690:             if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
691:                 $redir = $this->loginRedirect;
692:             }
693:         } else {
694:             $redir = $this->loginRedirect;
695:         }
696:         return Router::normalize($redir);
697:     }
698: /**
699:  * Validates a user against an abstract object.
700:  *
701:  * @param mixed $object  The object to validate the user against.
702:  * @param mixed $user    Optional.  The identity of the user to be validated.
703:  *                       Uses the current user session if none specified.  For
704:  *                       valid forms of identifying users, see
705:  *                       AuthComponent::identify().
706:  * @param string $action Optional. The action to validate against.
707:  * @see AuthComponent::identify()
708:  * @return boolean True if the user validates, false otherwise.
709:  * @access public
710:  */
711:     function validate($object, $user = null, $action = null) {
712:         if (empty($user)) {
713:             $user = $this->user();
714:         }
715:         if (empty($user)) {
716:             return false;
717:         }
718:         return $this->Acl->check($user, $object, $action);
719:     }
720: /**
721:  * Returns the path to the ACO node bound to a controller/action.
722:  *
723:  * @param string $action  Optional.  The controller/action path to validate the
724:  *                        user against.  The current request action is used if
725:  *                        none is specified.
726:  * @return boolean ACO node path
727:  * @access public
728:  */
729:     function action($action = ':controller/:action') {
730:         return str_replace(
731:             array(':controller', ':action'),
732:             array(Inflector::camelize($this->params['controller']), $this->params['action']),
733:             $this->actionPath . $action
734:         );
735:     }
736: /**
737:  * Returns a reference to the model object specified, and attempts
738:  * to load it if it is not found.
739:  *
740:  * @param string $name Model name (defaults to AuthComponent::$userModel)
741:  * @return object A reference to a model object
742:  * @access public
743:  */
744:     function &getModel($name = null) {
745:         $model = null;
746:         if (!$name) {
747:             $name = $this->userModel;
748:         }
749: 
750:         if (PHP5) {
751:             $model = ClassRegistry::init($name);
752:         } else {
753:             $model =& ClassRegistry::init($name);
754:         }
755: 
756:         if (empty($model)) {
757:             trigger_error(__('Auth::getModel() - Model is not set or could not be found', true), E_USER_WARNING);
758:             return null;
759:         }
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 = null;
775:         } elseif (is_array($conditions)) {
776:             $conditions = array_merge((array)$this->userScope, $conditions);
777:         } else {
778:             $conditions = $this->userScope;
779:         }
780:         if (empty($user)) {
781:             $user = $this->user();
782:             if (empty($user)) {
783:                 return null;
784:             }
785:         } elseif (is_object($user) && is_a($user, 'Model')) {
786:             if (!$user->exists()) {
787:                 return null;
788:             }
789:             $user = $user->read();
790:             $user = $user[$this->userModel];
791:         } elseif (is_array($user) && isset($user[$this->userModel])) {
792:             $user = $user[$this->userModel];
793:         }
794: 
795:         if (is_array($user) && (isset($user[$this->fields['username']]) || isset($user[$this->userModel . '.' . $this->fields['username']]))) {
796: 
797:             if (isset($user[$this->fields['username']]) && !empty($user[$this->fields['username']])  && !empty($user[$this->fields['password']])) {
798:                 if (trim($user[$this->fields['username']]) == '=' || trim($user[$this->fields['password']]) == '=') {
799:                     return false;
800:                 }
801:                 $find = array(
802:                     $this->userModel.'.'.$this->fields['username'] => $user[$this->fields['username']],
803:                     $this->userModel.'.'.$this->fields['password'] => $user[$this->fields['password']]
804:                 );
805:             } elseif (isset($user[$this->userModel . '.' . $this->fields['username']]) && !empty($user[$this->userModel . '.' . $this->fields['username']])) {
806:                 if (trim($user[$this->userModel . '.' . $this->fields['username']]) == '=' || trim($user[$this->userModel . '.' . $this->fields['password']]) == '=') {
807:                     return false;
808:                 }
809:                 $find = array(
810:                     $this->userModel.'.'.$this->fields['username'] => $user[$this->userModel . '.' . $this->fields['username']],
811:                     $this->userModel.'.'.$this->fields['password'] => $user[$this->userModel . '.' . $this->fields['password']]
812:                 );
813:             } else {
814:                 return false;
815:             }
816:             $model =& $this->getModel();
817:             $data = $model->find(array_merge($find, $conditions), null, null, 0);
818:             if (empty($data) || empty($data[$this->userModel])) {
819:                 return null;
820:             }
821:         } elseif (!empty($user) && is_string($user)) {
822:             $model =& $this->getModel();
823:             $data = $model->find(array_merge(array($model->escapeField() => $user), $conditions));
824: 
825:             if (empty($data) || empty($data[$this->userModel])) {
826:                 return null;
827:             }
828:         }
829: 
830:         if (!empty($data)) {
831:             if (!empty($data[$this->userModel][$this->fields['password']])) {
832:                 unset($data[$this->userModel][$this->fields['password']]);
833:             }
834:             return $data[$this->userModel];
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:  */
845:     function hashPasswords($data) {
846:         if (is_object($this->authenticate) && method_exists($this->authenticate, 'hashPasswords')) {
847:             return $this->authenticate->hashPasswords($data);
848:         }
849: 
850:         if (is_array($data) && isset($data[$this->userModel])) {
851:             if (isset($data[$this->userModel][$this->fields['username']]) && isset($data[$this->userModel][$this->fields['password']])) {
852:                 $data[$this->userModel][$this->fields['password']] = $this->password($data[$this->userModel][$this->fields['password']]);
853:             }
854:         }
855:         return $data;
856:     }
857: /**
858:  * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
859:  *
860:  * @param string $password Password to hash
861:  * @return string Hashed password
862:  * @access public
863:  */
864:     function password($password) {
865:         return Security::hash($password, null, true);
866:     }
867: /**
868:  * Component shutdown.  If user is logged in, wipe out redirect.
869:  *
870:  * @param object $controller Instantiating controller
871:  * @access public
872:  */
873:     function shutdown(&$controller) {
874:         if ($this->_loggedIn) {
875:             $this->Session->del('Auth.redirect');
876:         }
877:     }
878: }
879: ?>
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs