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 2.10 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 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

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • AclComponent
  • AuthComponent
  • CookieComponent
  • EmailComponent
  • FlashComponent
  • PaginatorComponent
  • RequestHandlerComponent
  • SecurityComponent
  • SessionComponent
  1: <?php
  2: /**
  3:  * Authentication component
  4:  *
  5:  * Manages user logins and permissions.
  6:  *
  7:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  8:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  9:  *
 10:  * Licensed under The MIT License
 11:  * For full copyright and license information, please see the LICENSE.txt
 12:  * Redistributions of files must retain the above copyright notice.
 13:  *
 14:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 15:  * @link          https://cakephp.org CakePHP(tm) Project
 16:  * @package       Cake.Controller.Component
 17:  * @since         CakePHP(tm) v 0.10.0.1076
 18:  * @license       https://opensource.org/licenses/mit-license.php MIT License
 19:  */
 20: 
 21: App::uses('Component', 'Controller');
 22: App::uses('Router', 'Routing');
 23: App::uses('Security', 'Utility');
 24: App::uses('Debugger', 'Utility');
 25: App::uses('Hash', 'Utility');
 26: App::uses('CakeSession', 'Model/Datasource');
 27: App::uses('BaseAuthorize', 'Controller/Component/Auth');
 28: App::uses('BaseAuthenticate', 'Controller/Component/Auth');
 29: App::uses('CakeEvent', 'Event');
 30: 
 31: /**
 32:  * Authentication control component class
 33:  *
 34:  * Binds access control with user authentication and session management.
 35:  *
 36:  * @package       Cake.Controller.Component
 37:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
 38:  */
 39: class AuthComponent extends Component {
 40: 
 41: /**
 42:  * Constant for 'all'
 43:  *
 44:  * @var string
 45:  */
 46:     const ALL = 'all';
 47: 
 48: /**
 49:  * Other components utilized by AuthComponent
 50:  *
 51:  * @var array
 52:  */
 53:     public $components = array('Session', 'Flash', 'RequestHandler');
 54: 
 55: /**
 56:  * An array of authentication objects to use for authenticating users. You can configure
 57:  * multiple adapters and they will be checked sequentially when users are identified.
 58:  *
 59:  * ```
 60:  *  $this->Auth->authenticate = array(
 61:  *      'Form' => array(
 62:  *          'userModel' => 'Users.User'
 63:  *      )
 64:  *  );
 65:  * ```
 66:  *
 67:  * Using the class name without 'Authenticate' as the key, you can pass in an array of settings for each
 68:  * authentication object. Additionally you can define settings that should be set to all authentications objects
 69:  * using the 'all' key:
 70:  *
 71:  * ```
 72:  *  $this->Auth->authenticate = array(
 73:  *      'all' => array(
 74:  *          'userModel' => 'Users.User',
 75:  *          'scope' => array('User.active' => 1)
 76:  *      ),
 77:  *      'Form',
 78:  *      'Basic'
 79:  *  );
 80:  * ```
 81:  *
 82:  * You can also use AuthComponent::ALL instead of the string 'all'.
 83:  *
 84:  * @var array
 85:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
 86:  */
 87:     public $authenticate = array('Form');
 88: 
 89: /**
 90:  * Objects that will be used for authentication checks.
 91:  *
 92:  * @var BaseAuthenticate[]
 93:  */
 94:     protected $_authenticateObjects = array();
 95: 
 96: /**
 97:  * An array of authorization objects to use for authorizing users. You can configure
 98:  * multiple adapters and they will be checked sequentially when authorization checks are done.
 99:  *
100:  * ```
101:  *  $this->Auth->authorize = array(
102:  *      'Crud' => array(
103:  *          'actionPath' => 'controllers/'
104:  *      )
105:  *  );
106:  * ```
107:  *
108:  * Using the class name without 'Authorize' as the key, you can pass in an array of settings for each
109:  * authorization object. Additionally you can define settings that should be set to all authorization objects
110:  * using the 'all' key:
111:  *
112:  * ```
113:  *  $this->Auth->authorize = array(
114:  *      'all' => array(
115:  *          'actionPath' => 'controllers/'
116:  *      ),
117:  *      'Crud',
118:  *      'CustomAuth'
119:  *  );
120:  * ```
121:  *
122:  * You can also use AuthComponent::ALL instead of the string 'all'
123:  *
124:  * @var mixed
125:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
126:  */
127:     public $authorize = false;
128: 
129: /**
130:  * Objects that will be used for authorization checks.
131:  *
132:  * @var BaseAuthorize[]
133:  */
134:     protected $_authorizeObjects = array();
135: 
136: /**
137:  * The name of an optional view element to render when an Ajax request is made
138:  * with an invalid or expired session
139:  *
140:  * @var string
141:  */
142:     public $ajaxLogin = null;
143: 
144: /**
145:  * Settings to use when Auth needs to do a flash message with SessionComponent::setFlash().
146:  * Available keys are:
147:  *
148:  * - `element` - The element to use, defaults to 'default'.
149:  * - `key` - The key to use, defaults to 'auth'
150:  * - `params` - The array of additional params to use, defaults to array()
151:  *
152:  * @var array
153:  */
154:     public $flash = array(
155:         'element' => 'default',
156:         'key' => 'auth',
157:         'params' => array()
158:     );
159: 
160: /**
161:  * The session key name where the record of the current user is stored. Default
162:  * key is "Auth.User". If you are using only stateless authenticators set this
163:  * to false to ensure session is not started.
164:  *
165:  * @var string
166:  */
167:     public static $sessionKey = 'Auth.User';
168: 
169: /**
170:  * The current user, used for stateless authentication when
171:  * sessions are not available.
172:  *
173:  * @var array
174:  */
175:     protected static $_user = array();
176: 
177: /**
178:  * A URL (defined as a string or array) to the controller action that handles
179:  * logins. Defaults to `/users/login`.
180:  *
181:  * @var mixed
182:  */
183:     public $loginAction = array(
184:         'controller' => 'users',
185:         'action' => 'login',
186:         'plugin' => null
187:     );
188: 
189: /**
190:  * Normally, if a user is redirected to the $loginAction page, the location they
191:  * were redirected from will be stored in the session so that they can be
192:  * redirected back after a successful login. If this session value is not
193:  * set, redirectUrl() method will return the URL specified in $loginRedirect.
194:  *
195:  * @var mixed
196:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$loginRedirect
197:  */
198:     public $loginRedirect = null;
199: 
200: /**
201:  * The default action to redirect to after the user is logged out. While AuthComponent does
202:  * not handle post-logout redirection, a redirect URL will be returned from AuthComponent::logout().
203:  * Defaults to AuthComponent::$loginAction.
204:  *
205:  * @var mixed
206:  * @see AuthComponent::$loginAction
207:  * @see AuthComponent::logout()
208:  */
209:     public $logoutRedirect = null;
210: 
211: /**
212:  * Error to display when user attempts to access an object or action to which they do not have
213:  * access.
214:  *
215:  * @var string|bool
216:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$authError
217:  */
218:     public $authError = null;
219: 
220: /**
221:  * Controls handling of unauthorized access.
222:  * - For default value `true` unauthorized user is redirected to the referrer URL
223:  *   or AuthComponent::$loginRedirect or '/'.
224:  * - If set to a string or array the value is used as a URL to redirect to.
225:  * - If set to false a ForbiddenException exception is thrown instead of redirecting.
226:  *
227:  * @var mixed
228:  */
229:     public $unauthorizedRedirect = true;
230: 
231: /**
232:  * Controller actions for which user validation is not required.
233:  *
234:  * @var array
235:  * @see AuthComponent::allow()
236:  */
237:     public $allowedActions = array();
238: 
239: /**
240:  * Request object
241:  *
242:  * @var CakeRequest
243:  */
244:     public $request;
245: 
246: /**
247:  * Response object
248:  *
249:  * @var CakeResponse
250:  */
251:     public $response;
252: 
253: /**
254:  * Method list for bound controller.
255:  *
256:  * @var array
257:  */
258:     protected $_methods = array();
259: 
260: /**
261:  * Initializes AuthComponent for use in the controller.
262:  *
263:  * @param Controller $controller A reference to the instantiating controller object
264:  * @return void
265:  */
266:     public function initialize(Controller $controller) {
267:         $this->request = $controller->request;
268:         $this->response = $controller->response;
269:         $this->_methods = $controller->methods;
270: 
271:         if (Configure::read('debug') > 0) {
272:             Debugger::checkSecurityKeys();
273:         }
274:     }
275: 
276: /**
277:  * Main execution method. Handles redirecting of invalid users, and processing
278:  * of login form data.
279:  *
280:  * @param Controller $controller A reference to the instantiating controller object
281:  * @return bool
282:  */
283:     public function startup(Controller $controller) {
284:         $methods = array_flip(array_map('strtolower', $controller->methods));
285:         $action = strtolower($controller->request->params['action']);
286: 
287:         $isMissingAction = (
288:             $controller->scaffold === false &&
289:             !isset($methods[$action])
290:         );
291: 
292:         if ($isMissingAction) {
293:             return true;
294:         }
295: 
296:         if (!$this->_setDefaults()) {
297:             return false;
298:         }
299: 
300:         if ($this->_isAllowed($controller)) {
301:             $this->_getUser();
302:             return true;
303:         }
304: 
305:         if (!$this->_getUser()) {
306:             return $this->_unauthenticated($controller);
307:         }
308: 
309:         if ($this->_isLoginAction($controller) ||
310:             empty($this->authorize) ||
311:             $this->isAuthorized($this->user())
312:         ) {
313:             return true;
314:         }
315: 
316:         return $this->_unauthorized($controller);
317:     }
318: 
319: /**
320:  * Checks whether current action is accessible without authentication.
321:  *
322:  * @param Controller $controller A reference to the instantiating controller object
323:  * @return bool True if action is accessible without authentication else false
324:  */
325:     protected function _isAllowed(Controller $controller) {
326:         $action = strtolower($controller->request->params['action']);
327:         if (in_array($action, array_map('strtolower', $this->allowedActions))) {
328:             return true;
329:         }
330:         return false;
331:     }
332: 
333: /**
334:  * Handles unauthenticated access attempt. First the `unathenticated()` method
335:  * of the last authenticator in the chain will be called. The authenticator can
336:  * handle sending response or redirection as appropriate and return `true` to
337:  * indicate no furthur action is necessary. If authenticator returns null this
338:  * method redirects user to login action. If it's an ajax request and
339:  * $ajaxLogin is specified that element is rendered else a 403 http status code
340:  * is returned.
341:  *
342:  * @param Controller $controller A reference to the controller object.
343:  * @return bool True if current action is login action else false.
344:  */
345:     protected function _unauthenticated(Controller $controller) {
346:         if (empty($this->_authenticateObjects)) {
347:             $this->constructAuthenticate();
348:         }
349:         $auth = $this->_authenticateObjects[count($this->_authenticateObjects) - 1];
350:         if ($auth->unauthenticated($this->request, $this->response)) {
351:             return false;
352:         }
353: 
354:         if ($this->_isLoginAction($controller)) {
355:             if (empty($controller->request->data)) {
356:                 if (!$this->Session->check('Auth.redirect') && env('HTTP_REFERER')) {
357:                     $this->Session->write('Auth.redirect', $controller->referer(null, true));
358:                 }
359:             }
360:             return true;
361:         }
362: 
363:         if (!$controller->request->is('ajax') && !$controller->request->is('json')) {
364:             $this->flash($this->authError);
365:             $this->Session->write('Auth.redirect', $controller->request->here(false));
366:             $controller->redirect($this->loginAction);
367:             return false;
368:         }
369:         if (!empty($this->ajaxLogin)) {
370:             $controller->response->statusCode(403);
371:             $controller->viewPath = 'Elements';
372:             $response = $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
373:             $response->send();
374:             $this->_stop();
375:             return false;
376:         }
377:         $controller->response->statusCode(403);
378:         $controller->response->send();
379:         $this->_stop();
380:         return false;
381:     }
382: 
383: /**
384:  * Normalizes $loginAction and checks if current request URL is same as login action.
385:  *
386:  * @param Controller $controller A reference to the controller object.
387:  * @return bool True if current action is login action else false.
388:  */
389:     protected function _isLoginAction(Controller $controller) {
390:         $url = '';
391:         if (isset($controller->request->url)) {
392:             $url = $controller->request->url;
393:         }
394:         $url = Router::normalize($url);
395:         $loginAction = Router::normalize($this->loginAction);
396: 
397:         return $loginAction === $url;
398:     }
399: 
400: /**
401:  * Handle unauthorized access attempt
402:  *
403:  * @param Controller $controller A reference to the controller object
404:  * @return bool Returns false
405:  * @throws ForbiddenException
406:  * @see AuthComponent::$unauthorizedRedirect
407:  */
408:     protected function _unauthorized(Controller $controller) {
409:         if ($this->unauthorizedRedirect === false) {
410:             throw new ForbiddenException($this->authError);
411:         }
412: 
413:         $this->flash($this->authError);
414:         if ($this->unauthorizedRedirect === true) {
415:             $default = '/';
416:             if (!empty($this->loginRedirect)) {
417:                 $default = $this->loginRedirect;
418:             }
419:             $url = $controller->referer($default, true);
420:         } else {
421:             $url = $this->unauthorizedRedirect;
422:         }
423:         $controller->redirect($url);
424:         return false;
425:     }
426: 
427: /**
428:  * Attempts to introspect the correct values for object properties.
429:  *
430:  * @return bool True
431:  */
432:     protected function _setDefaults() {
433:         $defaults = array(
434:             'logoutRedirect' => $this->loginAction,
435:             'authError' => __d('cake', 'You are not authorized to access that location.')
436:         );
437:         foreach ($defaults as $key => $value) {
438:             if (!isset($this->{$key}) || $this->{$key} === true) {
439:                 $this->{$key} = $value;
440:             }
441:         }
442:         return true;
443:     }
444: 
445: /**
446:  * Check if the provided user is authorized for the request.
447:  *
448:  * Uses the configured Authorization adapters to check whether or not a user is authorized.
449:  * Each adapter will be checked in sequence, if any of them return true, then the user will
450:  * be authorized for the request.
451:  *
452:  * @param array|null $user The user to check the authorization of. If empty the user in the session will be used.
453:  * @param CakeRequest|null $request The request to authenticate for. If empty, the current request will be used.
454:  * @return bool True if $user is authorized, otherwise false
455:  */
456:     public function isAuthorized($user = null, CakeRequest $request = null) {
457:         if (empty($user) && !$this->user()) {
458:             return false;
459:         }
460:         if (empty($user)) {
461:             $user = $this->user();
462:         }
463:         if (empty($request)) {
464:             $request = $this->request;
465:         }
466:         if (empty($this->_authorizeObjects)) {
467:             $this->constructAuthorize();
468:         }
469:         foreach ($this->_authorizeObjects as $authorizer) {
470:             if ($authorizer->authorize($user, $request) === true) {
471:                 return true;
472:             }
473:         }
474:         return false;
475:     }
476: 
477: /**
478:  * Loads the authorization objects configured.
479:  *
480:  * @return mixed Either null when authorize is empty, or the loaded authorization objects.
481:  * @throws CakeException
482:  */
483:     public function constructAuthorize() {
484:         if (empty($this->authorize)) {
485:             return null;
486:         }
487:         $this->_authorizeObjects = array();
488:         $config = Hash::normalize((array)$this->authorize);
489:         $global = array();
490:         if (isset($config[AuthComponent::ALL])) {
491:             $global = $config[AuthComponent::ALL];
492:             unset($config[AuthComponent::ALL]);
493:         }
494:         foreach ($config as $class => $settings) {
495:             list($plugin, $class) = pluginSplit($class, true);
496:             $className = $class . 'Authorize';
497:             App::uses($className, $plugin . 'Controller/Component/Auth');
498:             if (!class_exists($className)) {
499:                 throw new CakeException(__d('cake_dev', 'Authorization adapter "%s" was not found.', $class));
500:             }
501:             if (!method_exists($className, 'authorize')) {
502:                 throw new CakeException(__d('cake_dev', 'Authorization objects must implement an %s method.', 'authorize()'));
503:             }
504:             $settings = array_merge($global, (array)$settings);
505:             $this->_authorizeObjects[] = new $className($this->_Collection, $settings);
506:         }
507:         return $this->_authorizeObjects;
508:     }
509: 
510: /**
511:  * Takes a list of actions in the current controller for which authentication is not required, or
512:  * no parameters to allow all actions.
513:  *
514:  * You can use allow with either an array, or var args.
515:  *
516:  * `$this->Auth->allow(array('edit', 'add'));` or
517:  * `$this->Auth->allow('edit', 'add');` or
518:  * `$this->Auth->allow();` to allow all actions
519:  *
520:  * @param string|array|null $action Controller action name or array of actions
521:  * @return void
522:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
523:  */
524:     public function allow($action = null) {
525:         $args = func_get_args();
526:         if (empty($args) || $action === null) {
527:             $this->allowedActions = $this->_methods;
528:             return;
529:         }
530:         if (isset($args[0]) && is_array($args[0])) {
531:             $args = $args[0];
532:         }
533:         $this->allowedActions = array_merge($this->allowedActions, $args);
534:     }
535: 
536: /**
537:  * Removes items from the list of allowed/no authentication required actions.
538:  *
539:  * You can use deny with either an array, or var args.
540:  *
541:  * `$this->Auth->deny(array('edit', 'add'));` or
542:  * `$this->Auth->deny('edit', 'add');` or
543:  * `$this->Auth->deny();` to remove all items from the allowed list
544:  *
545:  * @param string|array|null $action Controller action name or array of actions
546:  * @return void
547:  * @see AuthComponent::allow()
548:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
549:  */
550:     public function deny($action = null) {
551:         $args = func_get_args();
552:         if (empty($args) || $action === null) {
553:             $this->allowedActions = array();
554:             return;
555:         }
556:         if (isset($args[0]) && is_array($args[0])) {
557:             $args = $args[0];
558:         }
559:         foreach ($args as $arg) {
560:             $i = array_search($arg, $this->allowedActions);
561:             if (is_int($i)) {
562:                 unset($this->allowedActions[$i]);
563:             }
564:         }
565:         $this->allowedActions = array_values($this->allowedActions);
566:     }
567: 
568: /**
569:  * Maps action names to CRUD operations.
570:  *
571:  * Used for controller-based authentication. Make sure
572:  * to configure the authorize property before calling this method. As it delegates $map to all the
573:  * attached authorize objects.
574:  *
575:  * @param array $map Actions to map
576:  * @return array
577:  * @see BaseAuthorize::mapActions()
578:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
579:  * @deprecated 3.0.0 Map actions using `actionMap` config key on authorize objects instead
580:  */
581:     public function mapActions($map = array()) {
582:         if (empty($this->_authorizeObjects)) {
583:             $this->constructAuthorize();
584:         }
585:         $mappedActions = array();
586:         foreach ($this->_authorizeObjects as $auth) {
587:             $mappedActions = Hash::merge($mappedActions, $auth->mapActions($map));
588:         }
589:         if (empty($map)) {
590:             return $mappedActions;
591:         }
592: 
593:         return array();
594:     }
595: 
596: /**
597:  * Log a user in.
598:  *
599:  * If a $user is provided that data will be stored as the logged in user. If `$user` is empty or not
600:  * specified, the request will be used to identify a user. If the identification was successful,
601:  * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
602:  * will also change the session id in order to help mitigate session replays.
603:  *
604:  * @param array|null $user Either an array of user data, or null to identify a user using the current request.
605:  * @return bool True on login success, false on failure
606:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
607:  */
608:     public function login($user = null) {
609:         $this->_setDefaults();
610: 
611:         if (empty($user)) {
612:             $user = $this->identify($this->request, $this->response);
613:         }
614:         if ($user) {
615:             if (static::$sessionKey) {
616:                 $this->Session->renew();
617:                 $this->Session->write(static::$sessionKey, $user);
618:             } else {
619:                 static::$_user = $user;
620:             }
621:             $event = new CakeEvent('Auth.afterIdentify', $this, array('user' => $user));
622:             $this->_Collection->getController()->getEventManager()->dispatch($event);
623:         }
624:         return (bool)$this->user();
625:     }
626: 
627: /**
628:  * Log a user out.
629:  *
630:  * Returns the logout action to redirect to. Triggers the logout() method of
631:  * all the authenticate objects, so they can perform custom logout logic.
632:  * AuthComponent will remove the session data, so there is no need to do that
633:  * in an authentication object. Logging out will also renew the session id.
634:  * This helps mitigate issues with session replays.
635:  *
636:  * @return string AuthComponent::$logoutRedirect
637:  * @see AuthComponent::$logoutRedirect
638:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
639:  */
640:     public function logout() {
641:         $this->_setDefaults();
642:         if (empty($this->_authenticateObjects)) {
643:             $this->constructAuthenticate();
644:         }
645:         $user = $this->user();
646:         foreach ($this->_authenticateObjects as $auth) {
647:             $auth->logout($user);
648:         }
649:         static::$_user = array();
650:         $this->Session->delete(static::$sessionKey);
651:         $this->Session->delete('Auth.redirect');
652:         $this->Session->renew();
653:         return Router::normalize($this->logoutRedirect);
654:     }
655: 
656: /**
657:  * Get the current user.
658:  *
659:  * Will prefer the static user cache over sessions. The static user
660:  * cache is primarily used for stateless authentication. For stateful authentication,
661:  * cookies + sessions will be used.
662:  *
663:  * @param string|null $key field to retrieve. Leave null to get entire User record
664:  * @return mixed|null User record. or null if no user is logged in.
665:  * @link https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
666:  */
667:     public static function user($key = null) {
668:         if (!empty(static::$_user)) {
669:             $user = static::$_user;
670:         } elseif (static::$sessionKey && CakeSession::check(static::$sessionKey)) {
671:             $user = CakeSession::read(static::$sessionKey);
672:         } else {
673:             return null;
674:         }
675:         if ($key === null) {
676:             return $user;
677:         }
678:         return Hash::get($user, $key);
679:     }
680: 
681: /**
682:  * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
683:  * objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
684:  *
685:  * @return bool True if a user can be found, false if one cannot.
686:  */
687:     protected function _getUser() {
688:         $user = $this->user();
689:         if ($user) {
690:             $this->Session->delete('Auth.redirect');
691:             return true;
692:         }
693: 
694:         if (empty($this->_authenticateObjects)) {
695:             $this->constructAuthenticate();
696:         }
697:         foreach ($this->_authenticateObjects as $auth) {
698:             $result = $auth->getUser($this->request);
699:             if (!empty($result) && is_array($result)) {
700:                 static::$_user = $result;
701:                 return true;
702:             }
703:         }
704: 
705:         return false;
706:     }
707: 
708: /**
709:  * Backwards compatible alias for AuthComponent::redirectUrl().
710:  *
711:  * @param string|array|null $url Optional URL to write as the login redirect URL.
712:  * @return string Redirect URL
713:  * @deprecated 3.0.0 Since 2.3.0, use AuthComponent::redirectUrl() instead
714:  */
715:     public function redirect($url = null) {
716:         return $this->redirectUrl($url);
717:     }
718: 
719: /**
720:  * Get the URL a user should be redirected to upon login.
721:  *
722:  * Pass a URL in to set the destination a user should be redirected to upon
723:  * logging in.
724:  *
725:  * If no parameter is passed, gets the authentication redirect URL. The URL
726:  * returned is as per following rules:
727:  *
728:  *  - Returns the normalized URL from session Auth.redirect value if it is
729:  *    present and for the same domain the current app is running on.
730:  *  - If there is no session value and there is a $loginRedirect, the $loginRedirect
731:  *    value is returned.
732:  *  - If there is no session and no $loginRedirect, / is returned.
733:  *
734:  * @param string|array|null $url Optional URL to write as the login redirect URL.
735:  * @return string Redirect URL
736:  */
737:     public function redirectUrl($url = null) {
738:         if ($url !== null) {
739:             $redir = $url;
740:             $this->Session->write('Auth.redirect', $redir);
741:         } elseif ($this->Session->check('Auth.redirect')) {
742:             $redir = $this->Session->read('Auth.redirect');
743:             $this->Session->delete('Auth.redirect');
744: 
745:             if (Router::normalize($redir) === Router::normalize($this->loginAction)) {
746:                 $redir = $this->loginRedirect ?: '/';
747:             }
748:         } elseif ($this->loginRedirect) {
749:             $redir = $this->loginRedirect;
750:         } else {
751:             $redir = '/';
752:         }
753:         if (is_array($redir)) {
754:             return Router::url($redir + array('base' => false));
755:         }
756:         return $redir;
757:     }
758: 
759: /**
760:  * Use the configured authentication adapters, and attempt to identify the user
761:  * by credentials contained in $request.
762:  *
763:  * @param CakeRequest $request The request that contains authentication data.
764:  * @param CakeResponse $response The response
765:  * @return array|bool User record data, or false, if the user could not be identified.
766:  */
767:     public function identify(CakeRequest $request, CakeResponse $response) {
768:         if (empty($this->_authenticateObjects)) {
769:             $this->constructAuthenticate();
770:         }
771:         foreach ($this->_authenticateObjects as $auth) {
772:             $result = $auth->authenticate($request, $response);
773:             if (!empty($result) && is_array($result)) {
774:                 return $result;
775:             }
776:         }
777:         return false;
778:     }
779: 
780: /**
781:  * Loads the configured authentication objects.
782:  *
783:  * @return mixed Either null on empty authenticate value, or an array of loaded objects.
784:  * @throws CakeException
785:  */
786:     public function constructAuthenticate() {
787:         if (empty($this->authenticate)) {
788:             return null;
789:         }
790:         $this->_authenticateObjects = array();
791:         $config = Hash::normalize((array)$this->authenticate);
792:         $global = array();
793:         if (isset($config[AuthComponent::ALL])) {
794:             $global = $config[AuthComponent::ALL];
795:             unset($config[AuthComponent::ALL]);
796:         }
797:         foreach ($config as $class => $settings) {
798:             if (!empty($settings['className'])) {
799:                 $class = $settings['className'];
800:                 unset($settings['className']);
801:             }
802:             list($plugin, $class) = pluginSplit($class, true);
803:             $className = $class . 'Authenticate';
804:             App::uses($className, $plugin . 'Controller/Component/Auth');
805:             if (!class_exists($className)) {
806:                 throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class));
807:             }
808:             if (!method_exists($className, 'authenticate')) {
809:                 throw new CakeException(__d('cake_dev', 'Authentication objects must implement an %s method.', 'authenticate()'));
810:             }
811:             $settings = array_merge($global, (array)$settings);
812:             $auth = new $className($this->_Collection, $settings);
813:             $this->_Collection->getController()->getEventManager()->attach($auth);
814:             $this->_authenticateObjects[] = $auth;
815:         }
816:         return $this->_authenticateObjects;
817:     }
818: 
819: /**
820:  * Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
821:  *
822:  * This method is intended as a convenience wrapper for Security::hash(). If you want to use
823:  * a hashing/encryption system not supported by that method, do not use this method.
824:  *
825:  * @param string $password Password to hash
826:  * @return string Hashed password
827:  * @deprecated 3.0.0 Since 2.4. Use Security::hash() directly or a password hasher object.
828:  */
829:     public static function password($password) {
830:         return Security::hash($password, null, true);
831:     }
832: 
833: /**
834:  * Check whether or not the current user has data in the session, and is considered logged in.
835:  *
836:  * @return bool true if the user is logged in, false otherwise
837:  * @deprecated 3.0.0 Since 2.5. Use AuthComponent::user() directly.
838:  */
839:     public function loggedIn() {
840:         return (bool)$this->user();
841:     }
842: 
843: /**
844:  * Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
845:  *
846:  * @param string $message The message to set.
847:  * @return void
848:  */
849:     public function flash($message) {
850:         if ($message === false) {
851:             return;
852:         }
853:         $this->Flash->set($message, $this->flash);
854:     }
855: 
856: }
857: 
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