Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 761 lines (703 sloc) 22.688 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
<?php
/**
* Authentication component
*
* Manages user logins and permissions.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Controller.Component
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

App::uses('Component', 'Controller');
App::uses('Router', 'Routing');
App::uses('Security', 'Utility');
App::uses('Debugger', 'Utility');
App::uses('Hash', 'Utility');
App::uses('CakeSession', 'Model/Datasource');
App::uses('BaseAuthorize', 'Controller/Component/Auth');
App::uses('BaseAuthenticate', 'Controller/Component/Auth');

/**
* Authentication control component class
*
* Binds access control with user authentication and session management.
*
* @package Cake.Controller.Component
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
*/
class AuthComponent extends Component {

/**
* Constant for 'all'
*/
const ALL = 'all';

/**
* Other components utilized by AuthComponent
*
* @var array
*/
public $components = array('Session', 'RequestHandler');

/**
* An array of authentication objects to use for authenticating users. You can configure
* multiple adapters and they will be checked sequentially when users are identified.
*
* {{{
* $this->Auth->authenticate = array(
* 'Form' => array(
* 'userModel' => 'Users.User'
* )
* );
* }}}
*
* Using the class name without 'Authenticate' as the key, you can pass in an array of settings for each
* authentication object. Additionally you can define settings that should be set to all authentications objects
* using the 'all' key:
*
* {{{
* $this->Auth->authenticate = array(
* 'all' => array(
* 'userModel' => 'Users.User',
* 'scope' => array('User.active' => 1)
* ),
* 'Form',
* 'Basic'
* );
* }}}
*
* You can also use AuthComponent::ALL instead of the string 'all'.
*
* @var array
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
*/
public $authenticate = array('Form');

/**
* Objects that will be used for authentication checks.
*
* @var array
*/
protected $_authenticateObjects = array();

/**
* An array of authorization objects to use for authorizing users. You can configure
* multiple adapters and they will be checked sequentially when authorization checks are done.
*
* {{{
* $this->Auth->authorize = array(
* 'Crud' => array(
* 'actionPath' => 'controllers/'
* )
* );
* }}}
*
* Using the class name without 'Authorize' as the key, you can pass in an array of settings for each
* authorization object. Additionally you can define settings that should be set to all authorization objects
* using the 'all' key:
*
* {{{
* $this->Auth->authorize = array(
* 'all' => array(
* 'actionPath' => 'controllers/'
* ),
* 'Crud',
* 'CustomAuth'
* );
* }}}
*
* You can also use AuthComponent::ALL instead of the string 'all'
*
* @var mixed
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
*/
public $authorize = false;

/**
* Objects that will be used for authorization checks.
*
* @var array
*/
protected $_authorizeObjects = array();

/**
* The name of an optional view element to render when an Ajax request is made
* with an invalid or expired session
*
* @var string
*/
public $ajaxLogin = null;

/**
* Settings to use when Auth needs to do a flash message with SessionComponent::setFlash().
* Available keys are:
*
* - `element` - The element to use, defaults to 'default'.
* - `key` - The key to use, defaults to 'auth'
* - `params` - The array of additional params to use, defaults to array()
*
* @var array
*/
public $flash = array(
'element' => 'default',
'key' => 'auth',
'params' => array()
);

/**
* The session key name where the record of the current user is stored. If
* unspecified, it will be "Auth.User".
*
* @var string
*/
public static $sessionKey = 'Auth.User';

/**
* The current user, used for stateless authentication when
* sessions are not available.
*
* @var array
*/
protected static $_user = array();

/**
* A URL (defined as a string or array) to the controller action that handles
* logins. Defaults to `/users/login`
*
* @var mixed
*/
public $loginAction = array(
'controller' => 'users',
'action' => 'login',
'plugin' => null
);

/**
* Normally, if a user is redirected to the $loginAction page, the location they
* were redirected from will be stored in the session so that they can be
* redirected back after a successful login. If this session value is not
* set, the user will be redirected to the page specified in $loginRedirect.
*
* @var mixed
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$loginRedirect
*/
public $loginRedirect = null;

/**
* The default action to redirect to after the user is logged out. While AuthComponent does
* not handle post-logout redirection, a redirect URL will be returned from AuthComponent::logout().
* Defaults to AuthComponent::$loginAction.
*
* @var mixed
* @see AuthComponent::$loginAction
* @see AuthComponent::logout()
*/
public $logoutRedirect = null;

/**
* Error to display when user attempts to access an object or action to which they do not have
* access.
*
* @var string
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$authError
*/
public $authError = null;

/**
* Controls handling of unauthorized access.
* - For default value `true` unauthorized user is redirected to the referrer url
* or AuthComponent::$loginRedirect or '/'.
* - If set to a string or array the value is used as an url to redirect to.
* - If set to false a ForbiddenException exception is thrown instead of redirecting.
*
* @var mixed
*/
public $unauthorizedRedirect = true;

/**
* Controller actions for which user validation is not required.
*
* @var array
* @see AuthComponent::allow()
*/
public $allowedActions = array();

/**
* Request object
*
* @var CakeRequest
*/
public $request;

/**
* Response object
*
* @var CakeResponse
*/
public $response;

/**
* Method list for bound controller
*
* @var array
*/
protected $_methods = array();

/**
* Initializes AuthComponent for use in the controller
*
* @param Controller $controller A reference to the instantiating controller object
* @return void
*/
public function initialize(Controller $controller) {
$this->request = $controller->request;
$this->response = $controller->response;
$this->_methods = $controller->methods;

if (Configure::read('debug') > 0) {
Debugger::checkSecurityKeys();
}
}

/**
* Main execution method. Handles redirecting of invalid users, and processing
* of login form data.
*
* @param Controller $controller A reference to the instantiating controller object
* @return boolean
*/
public function startup(Controller $controller) {
$methods = array_flip(array_map('strtolower', $controller->methods));
$action = strtolower($controller->request->params['action']);

$isMissingAction = (
$controller->scaffold === false &&
!isset($methods[$action])
);

if ($isMissingAction) {
return true;
}

if (!$this->_setDefaults()) {
return false;
}
$request = $controller->request;

$url = '';

if (isset($request->url)) {
$url = $request->url;
}
$url = Router::normalize($url);
$loginAction = Router::normalize($this->loginAction);

if ($loginAction != $url && in_array($action, array_map('strtolower', $this->allowedActions))) {
return true;
}

if ($loginAction == $url) {
if (empty($request->data)) {
if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
$this->Session->write('Auth.redirect', $controller->referer(null, true));
}
}
return true;
}

if (!$this->_getUser()) {
if (!$request->is('ajax')) {
$this->flash($this->authError);
$this->Session->write('Auth.redirect', $request->here());
$controller->redirect($loginAction);
return false;
}
if (!empty($this->ajaxLogin)) {
$controller->viewPath = 'Elements';
echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
$this->_stop();
return false;
}
$controller->redirect(null, 403);
}

if (empty($this->authorize) || $this->isAuthorized($this->user())) {
return true;
}

return $this->_unauthorized($controller);
}

/**
* Handle unauthorized access attempt
*
* @param Controller $controller A reference to the controller object
* @return boolean Returns false
* @throws ForbiddenException
*/
protected function _unauthorized(Controller $controller) {
if ($this->unauthorizedRedirect === false) {
throw new ForbiddenException($this->authError);
}

$this->flash($this->authError);
if ($this->unauthorizedRedirect === true) {
$default = '/';
if (!empty($this->loginRedirect)) {
$default = $this->loginRedirect;
}
$url = $controller->referer($default, true);
} else {
$url = $this->unauthorizedRedirect;
}
$controller->redirect($url, null, true);
return false;
}

/**
* Attempts to introspect the correct values for object properties.
*
* @return boolean
*/
protected function _setDefaults() {
$defaults = array(
'logoutRedirect' => $this->loginAction,
'authError' => __d('cake', 'You are not authorized to access that location.')
);
foreach ($defaults as $key => $value) {
if (empty($this->{$key})) {
$this->{$key} = $value;
}
}
return true;
}

/**
* Uses the configured Authorization adapters to check whether or not a user is authorized.
* Each adapter will be checked in sequence, if any of them return true, then the user will
* be authorized for the request.
*
* @param array $user The user to check the authorization of. If empty the user in the session will be used.
* @param CakeRequest $request The request to authenticate for. If empty, the current request will be used.
* @return boolean True if $user is authorized, otherwise false
*/
public function isAuthorized($user = null, $request = null) {
if (empty($user) && !$this->user()) {
return false;
}
if (empty($user)) {
$user = $this->user();
}
if (empty($request)) {
$request = $this->request;
}
if (empty($this->_authorizeObjects)) {
$this->constructAuthorize();
}
foreach ($this->_authorizeObjects as $authorizer) {
if ($authorizer->authorize($user, $request) === true) {
return true;
}
}
return false;
}

/**
* Loads the authorization objects configured.
*
* @return mixed Either null when authorize is empty, or the loaded authorization objects.
* @throws CakeException
*/
public function constructAuthorize() {
if (empty($this->authorize)) {
return;
}
$this->_authorizeObjects = array();
$config = Hash::normalize((array)$this->authorize);
$global = array();
if (isset($config[AuthComponent::ALL])) {
$global = $config[AuthComponent::ALL];
unset($config[AuthComponent::ALL]);
}
foreach ($config as $class => $settings) {
list($plugin, $class) = pluginSplit($class, true);
$className = $class . 'Authorize';
App::uses($className, $plugin . 'Controller/Component/Auth');
if (!class_exists($className)) {
throw new CakeException(__d('cake_dev', 'Authorization adapter "%s" was not found.', $class));
}
if (!method_exists($className, 'authorize')) {
throw new CakeException(__d('cake_dev', 'Authorization objects must implement an authorize method.'));
}
$settings = array_merge($global, (array)$settings);
$this->_authorizeObjects[] = new $className($this->_Collection, $settings);
}
return $this->_authorizeObjects;
}

/**
* Takes a list of actions in the current controller for which authentication is not required, or
* no parameters to allow all actions.
*
* You can use allow with either an array, or var args.
*
* `$this->Auth->allow(array('edit', 'add'));` or
* `$this->Auth->allow('edit', 'add');` or
* `$this->Auth->allow();` to allow all actions
*
* @param string|array $action,... Controller action name or array of actions
* @return void
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public
*/
public function allow($action = null) {
$args = func_get_args();
if (empty($args) || $action === null) {
$this->allowedActions = $this->_methods;
return;
}
if (isset($args[0]) && is_array($args[0])) {
$args = $args[0];
}
$this->allowedActions = array_merge($this->allowedActions, $args);
}

/**
* Removes items from the list of allowed/no authentication required actions.
*
* You can use deny with either an array, or var args.
*
* `$this->Auth->deny(array('edit', 'add'));` or
* `$this->Auth->deny('edit', 'add');` or
* `$this->Auth->deny();` to remove all items from the allowed list
*
* @param string|array $action,... Controller action name or array of actions
* @return void
* @see AuthComponent::allow()
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization
*/
public function deny($action = null) {
$args = func_get_args();
if (empty($args) || $action === null) {
$this->allowedActions = array();
return;
}
if (isset($args[0]) && is_array($args[0])) {
$args = $args[0];
}
foreach ($args as $arg) {
$i = array_search($arg, $this->allowedActions);
if (is_int($i)) {
unset($this->allowedActions[$i]);
}
}
$this->allowedActions = array_values($this->allowedActions);
}

/**
* Maps action names to CRUD operations. Used for controller-based authentication. Make sure
* to configure the authorize property before calling this method. As it delegates $map to all the
* attached authorize objects.
*
* @param array $map Actions to map
* @return void
* @see BaseAuthorize::mapActions()
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize
*/
public function mapActions($map = array()) {
if (empty($this->_authorizeObjects)) {
$this->constructAuthorize();
}
foreach ($this->_authorizeObjects as $auth) {
$auth->mapActions($map);
}
}

/**
* Log a user in. If a $user is provided that data will be stored as the logged in user. If `$user` is empty or not
* specified, the request will be used to identify a user. If the identification was successful,
* the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
* will also change the session id in order to help mitigate session replays.
*
* @param array $user Either an array of user data, or null to identify a user using the current request.
* @return boolean True on login success, false on failure
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
*/
public function login($user = null) {
$this->_setDefaults();

if (empty($user)) {
$user = $this->identify($this->request, $this->response);
}
if ($user) {
$this->Session->renew();
$this->Session->write(self::$sessionKey, $user);
}
return $this->loggedIn();
}

/**
* Logs a user out, and returns the login action to redirect to.
* Triggers the logout() method of all the authenticate objects, so they can perform
* custom logout logic. AuthComponent will remove the session data, so
* there is no need to do that in an authentication object. Logging out
* will also renew the session id. This helps mitigate issues with session replays.
*
* @return string AuthComponent::$logoutRedirect
* @see AuthComponent::$logoutRedirect
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out
*/
public function logout() {
$this->_setDefaults();
if (empty($this->_authenticateObjects)) {
$this->constructAuthenticate();
}
$user = $this->user();
foreach ($this->_authenticateObjects as $auth) {
$auth->logout($user);
}
$this->Session->delete(self::$sessionKey);
$this->Session->delete('Auth.redirect');
$this->Session->renew();
return Router::normalize($this->logoutRedirect);
}

/**
* Get the current user.
*
* Will prefer the static user cache over sessions. The static user
* cache is primarily used for stateless authentication. For stateful authentication,
* cookies + sessions will be used.
*
* @param string $key field to retrieve. Leave null to get entire User record
* @return mixed User record. or null if no user is logged in.
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user
*/
public static function user($key = null) {
if (empty(self::$_user) && !CakeSession::check(self::$sessionKey)) {
return null;
}
if (!empty(self::$_user)) {
$user = self::$_user;
} else {
$user = CakeSession::read(self::$sessionKey);
}
if ($key === null) {
return $user;
}
return Hash::get($user, $key);
}

/**
* Similar to AuthComponent::user() except if the session user cannot be found, connected authentication
* objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
*
* @return boolean true if a user can be found, false if one cannot.
*/
protected function _getUser() {
$user = $this->user();
if ($user) {
return true;
}
if (empty($this->_authenticateObjects)) {
$this->constructAuthenticate();
}
foreach ($this->_authenticateObjects as $auth) {
$result = $auth->getUser($this->request);
if (!empty($result) && is_array($result)) {
self::$_user = $result;
return true;
}
}
return false;
}

/**
* Backwards compatible alias for AuthComponent::redirectUrl()
*
* @param string|array $url Optional URL to write as the login redirect URL.
* @return string Redirect URL
* @deprecated 2.3 Use AuthComponent::redirectUrl() instead
*/
public function redirect($url = null) {
return $this->redirectUrl($url);
}

/**
* If no parameter is passed, gets the authentication redirect URL. Pass a url in to
* set the destination a user should be redirected to upon logging in. Will fallback to
* AuthComponent::$loginRedirect if there is no stored redirect value.
*
* @param string|array $url Optional URL to write as the login redirect URL.
* @return string Redirect URL
*/
public function redirectUrl($url = null) {
if (!is_null($url)) {
$redir = $url;
$this->Session->write('Auth.redirect', $redir);
} elseif ($this->Session->check('Auth.redirect')) {
$redir = $this->Session->read('Auth.redirect');
$this->Session->delete('Auth.redirect');

if (Router::normalize($redir) == Router::normalize($this->loginAction)) {
$redir = $this->loginRedirect;
}
} else {
$redir = $this->loginRedirect;
}
return Router::normalize($redir);
}

/**
* Use the configured authentication adapters, and attempt to identify the user
* by credentials contained in $request.
*
* @param CakeRequest $request The request that contains authentication data.
* @param CakeResponse $response The response
* @return array User record data, or false, if the user could not be identified.
*/
public function identify(CakeRequest $request, CakeResponse $response) {
if (empty($this->_authenticateObjects)) {
$this->constructAuthenticate();
}
foreach ($this->_authenticateObjects as $auth) {
$result = $auth->authenticate($request, $response);
if (!empty($result) && is_array($result)) {
return $result;
}
}
return false;
}

/**
* loads the configured authentication objects.
*
* @return mixed either null on empty authenticate value, or an array of loaded objects.
* @throws CakeException
*/
public function constructAuthenticate() {
if (empty($this->authenticate)) {
return;
}
$this->_authenticateObjects = array();
$config = Hash::normalize((array)$this->authenticate);
$global = array();
if (isset($config[AuthComponent::ALL])) {
$global = $config[AuthComponent::ALL];
unset($config[AuthComponent::ALL]);
}
foreach ($config as $class => $settings) {
list($plugin, $class) = pluginSplit($class, true);
$className = $class . 'Authenticate';
App::uses($className, $plugin . 'Controller/Component/Auth');
if (!class_exists($className)) {
throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class));
}
if (!method_exists($className, 'authenticate')) {
throw new CakeException(__d('cake_dev', 'Authentication objects must implement an authenticate method.'));
}
$settings = array_merge($global, (array)$settings);
$this->_authenticateObjects[] = new $className($this->_Collection, $settings);
}
return $this->_authenticateObjects;
}

/**
* Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
*
* This method is intended as a convenience wrapper for Security::hash(). If you want to use
* a hashing/encryption system not supported by that method, do not use this method.
*
* @param string $password Password to hash
* @return string Hashed password
* @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords
*/
public static function password($password) {
return Security::hash($password, null, true);
}

/**
* Component shutdown. If user is logged in, wipe out redirect.
*
* @param Controller $controller Instantiating controller
* @return void
*/
public function shutdown(Controller $controller) {
if ($this->loggedIn()) {
$this->Session->delete('Auth.redirect');
}
}

/**
* Check whether or not the current user has data in the session, and is considered logged in.
*
* @return boolean true if the user is logged in, false otherwise
*/
public function loggedIn() {
return $this->user() != array();
}

/**
* Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
*
* @param string $message The message to set.
* @return void
*/
public function flash($message) {
$this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']);
}

}
Something went wrong with that request. Please try again.