Class AuthComponent
Authentication control component class
Binds access control with user authentication and session management.
Link: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
Copyright: Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Location: Cake/Controller/Component/AuthComponent.php
Constants summary
-
string
ALL
¶'all'
Properties summary
-
$_authenticateObjects
protectedarray
Objects that will be used for authentication checks. -
$_authorizeObjects
protectedarray
Objects that will be used for authorization checks. -
$_methods
protectedarray
Method list for bound controller -
$_user
protected staticarray
The current user, used for stateless authentication when sessions are not available.
-
$ajaxLogin
publicstring
The name of an optional view element to render when an Ajax request is made with an invalid or expired session
-
$allowedActions
publicarray
Controller actions for which user validation is not required. -
$authError
publicstring
Error to display when user attempts to access an object or action to which they do not have access.
-
$authenticate
publicarray
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.
-
$authorize
publicmixed
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.
-
$components
publicarray
Other components utilized by AuthComponent -
$flash
publicarray
Settings to use when Auth needs to do a flash message with SessionComponent::setFlash(). Available keys are:
-
$loginAction
publicmixed
A URL (defined as a string or array) to the controller action that handles logins. Defaults to
/users/login
-
$loginRedirect
publicmixed
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.
-
$logoutRedirect
publicmixed
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.
-
$request
publicRequest object -
$response
publicResponse object -
$sessionKey
public staticstring
The session key name where the record of the current user is stored. If unspecified, it will be "Auth.User".
Inherited Properties
Method Summary
-
_getUser() protected
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.
-
_setDefaults() protected
Attempts to introspect the correct values for object properties. -
allow() public
Takes a list of actions in the current controller for which authentication is not required, or no parameters to allow all actions.
-
constructAuthenticate() public
loads the configured authentication objects. -
constructAuthorize() public
Loads the authorization objects configured. -
deny() public
Removes items from the list of allowed/no authentication required actions. -
flash() public
Set a flash message. Uses the Session component, and values from AuthComponent::$flash. -
identify() public
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
-
initialize() public
Initializes AuthComponent for use in the controller -
isAuthorized() public
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.
-
loggedIn() public
Check whether or not the current user has data in the session, and is considered logged in. -
login() public
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. -
logout() public
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.
-
mapActions() public
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.
-
password() public static
Hash a password with the application's salt value (as defined with Configure::write('Security.salt'); -
redirect() public
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.
-
shutdown() public
Component shutdown. If user is logged in, wipe out redirect. -
startup() public
Main execution method. Handles redirecting of invalid users, and processing of login form data.
-
user() public static
Get the current user.
Method Detail
_getUser() protected ¶
_getUser( )
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.
Returns
true if a user can be found, false if one cannot.
_setDefaults() protected ¶
_setDefaults( )
Attempts to introspect the correct values for object properties.
Returns
allow() public ¶
allow( mixed $action = null )
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');
$this->Auth->allow();
to allow all actions.
allow() also supports '*' as a wildcard to mean all actions.
$this->Auth->allow('*');
Parameters
- mixed $action optional null
- Controller action name or array of actions
Link
constructAuthenticate() public ¶
constructAuthenticate( )
loads the configured authentication objects.
Returns
either null on empty authenticate value, or an array of loaded objects.
Throws
constructAuthorize() public ¶
constructAuthorize( )
Loads the authorization objects configured.
Returns
Either null when authorize is empty, or the loaded authorization objects.
Throws
deny() public ¶
deny( mixed $action = null )
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
Parameters
- mixed $action optional null
- Controller action name or array of actions
See
Link
flash() public ¶
flash( string $message )
Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
Parameters
- string $message
- The message to set.
identify() public ¶
identify( CakeRequest
$request , CakeResponse
$response )
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
Parameters
-
CakeRequest
$request - The request that contains authentication data.
-
CakeResponse
$response - The response
Returns
User record data, or false, if the user could not be identified.
initialize() public ¶
initialize( Controller
$controller )
Initializes AuthComponent for use in the controller
Parameters
-
Controller
$controller - A reference to the instantiating controller object
Overrides
isAuthorized() public ¶
isAuthorized( mixed $user = null , CakeRequest
$request = null )
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.
Parameters
- mixed $user optional null
- The user to check the authorization of. If empty the user in the session will be used.
-
CakeRequest
$request optional null - The request to authenticate for. If empty, the current request will be used.
Returns
True if $user is authorized, otherwise false
loggedIn() public ¶
loggedIn( )
Check whether or not the current user has data in the session, and is considered logged in.
Returns
true if the user is logged in, false otherwise
login() public ¶
login( mixed $user = null )
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.
Parameters
- mixed $user optional null
- Either an array of user data, or null to identify a user using the current request.
Returns
True on login success, false on failure
Link
logout() public ¶
logout( )
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.
Returns
AuthComponent::$logoutRedirect
See
Link
mapActions() public ¶
mapActions( array $map = array() )
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.
Parameters
- array $map optional array()
- Actions to map
See
Link
password() public static ¶
password( string $password )
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.
Parameters
- string $password
- Password to hash
Returns
Hashed password
Link
redirect() public ¶
redirect( mixed $url = null )
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.
Parameters
- mixed $url optional null
- Optional URL to write as the login redirect URL.
Returns
Redirect URL
shutdown() public ¶
shutdown( Controller
$controller )
Component shutdown. If user is logged in, wipe out redirect.
Parameters
-
Controller
$controller - Instantiating controller
Overrides
startup() public ¶
startup( Controller
$controller )
Main execution method. Handles redirecting of invalid users, and processing of login form data.
Parameters
-
Controller
$controller - A reference to the instantiating controller object
Returns
Overrides
user() public static ¶
user( string $key = null )
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.
Parameters
- string $key optional null
- field to retrieve. Leave null to get entire User record
Returns
User record. or null if no user is logged in.
Link
Methods inherited from Component
__construct() public ¶
__construct( ComponentCollection
$collection , array $settings = array() )
Constructor
Parameters
-
ComponentCollection
$collection - A ComponentCollection this component can use to lazy load its components
- array $settings optional array()
- Array of configuration settings.
Overrides
__get() public ¶
__get( string $name )
Magic method for lazy loading $components.
Parameters
- string $name
- Name of component to get.
Returns
A Component object or null.
beforeRedirect() public ¶
beforeRedirect( Controller
$controller , string|array $url , integer $status = null , boolean $exit = true )
Called before Controller::redirect(). Allows you to replace the url that will be redirected to with a new url. The return of this method can either be an array or a string.
If the return is an array and contains a 'url' key. You may also supply the following:
status
The status code for the redirectexit
Whether or not the redirect should exit.
If your response is a string or an array that does not contain a 'url' key it will be used as the new url to redirect to.
Parameters
-
Controller
$controller - Controller with components to beforeRedirect
- string|array $url
- Either the string or url array that is being redirected to.
- integer $status optional null
- The status code of the redirect
- boolean $exit optional true
- Will the script exit.
Returns
Either an array or null.
Link
beforeRender() public ¶
beforeRender( Controller
$controller )
Called after the Controller::beforeRender(), after the view class is loaded, and before the Controller::render()
Parameters
-
Controller
$controller - Controller with components to beforeRender
Link
Methods inherited from Object
_mergeVars() protected ¶
_mergeVars( array $properties , string $class , boolean $normalize = true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
Parameters
- array $properties
- The name of the properties to merge.
- string $class
- The class to merge the property with.
- boolean $normalize optional true
- Set to true to run the properties through Set::normalize() before merging.
_set() protected ¶
_set( array $properties = array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
Parameters
- array $properties optional array()
- An associative array containing properties and corresponding values.
_stop() protected ¶
_stop( integer|string $status = 0 )
Stop execution of the current script. Wraps exit() making testing easier.
Parameters
- integer|string $status optional 0
- see http://php.net/exit for values
dispatchMethod() public ¶
dispatchMethod( string $method , array $params = array() )
Calls a method on this object with the given parameters. Provides an OO wrapper
for call_user_func_array
Parameters
- string $method
- Name of the method to call
- array $params optional array()
- Parameter list to use when calling $method
Returns
Returns the result of the method call
log() public ¶
log( string $msg , integer $type = LOG_ERROR )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
Parameters
- string $msg
- Log message
- integer $type optional LOG_ERROR
- Error type constant. Defined in app/Config/core.php.
Returns
Success of log write
requestAction() public ¶
requestAction( mixed $url , array $extra = array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
Passing POST and GET data
POST and GET data can be simulated in requestAction. Use $extra['url']
for
GET data. The $extra['data']
parameter allows POST data simulation.
Parameters
- mixed $url
String or array-based url. Unlike other url arrays in CakePHP, this url will not automatically handle passed and named arguments in the $url parameter.
- array $extra optional array()
if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.
Returns
Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString() public ¶
toString( )
Object-to-string conversion. Each class can override this method as necessary.
Returns
The name of this class
Properties detail
$_authenticateObjects ¶
Objects that will be used for authentication checks.
array()
$_user ¶
The current user, used for stateless authentication when sessions are not available.
array()
$ajaxLogin ¶
The name of an optional view element to render when an Ajax request is made with an invalid or expired session
null
$allowedActions ¶
Controller actions for which user validation is not required.
See
array()
$authError ¶
Error to display when user attempts to access an object or action to which they do not have access.
Link
null
$authenticate ¶
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'.
Link
array('Form')
$authorize ¶
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'
Link
false
$components ¶
Other components utilized by AuthComponent
array('Session', 'RequestHandler')
$flash ¶
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()
array( 'element' => 'default', 'key' => 'auth', 'params' => array() )
$loginAction ¶
A URL (defined as a string or array) to the controller action that handles
logins. Defaults to /users/login
array( 'controller' => 'users', 'action' => 'login', 'plugin' => null )
$loginRedirect ¶
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.
Link
null
$logoutRedirect ¶
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.
See
AuthComponent::logout()
null
$sessionKey ¶
The session key name where the record of the current user is stored. If unspecified, it will be "Auth.User".
'Auth.User'