Welcome to the Cookbook

loading...

5.2.6 Atributos de AuthComponent

Ahora hay varias variables relacionadas con Auth que también puedes utilizar. Normalmente añades esta configuración en el método beforeFilter() de tu controlador. Si necesitas aplicar dicha configuración a todo el sitio, deberías añadirla a beforeFilter() de AppController.

5.2.6.1 userModel

¿No deseas utilizar un modelo User contra el que autenticar? No hay problema. Simplemente cámbialo configurando este valor con el nombre del modelo que deseas usar.

<?php
    $this->Auth->userModel = 'Miembro';
?>
  1. <?php
  2. $this->Auth->userModel = 'Miembro';
  3. ?>

5.2.6.2 fields

Sobreescribe los campos de usuario y contraseña por defecto usados para la autenticación.

<?php
    $this->Auth->fields = array('username' => 'email', 'password' => 'passwd');
?>
  1. <?php
  2. $this->Auth->fields = array('username' => 'email', 'password' => 'passwd');
  3. ?>

5.2.6.3 userScope

Utiliza esto para añadir requisitos adicionales para que la autenticación sea exitosa.

<?php
    $this->Auth->userScope = array('User.activo' => true);
?>
  1. <?php
  2. $this->Auth->userScope = array('User.activo' => true);
  3. ?>

5.2.6.4 loginAction

Puedes cambiar el login por defecto de /users/login para que sea cualquier acción a tu elección.

<?php
    $this->Auth->loginAction = array('admin' => false, 'controller' => 'miembros', 'action' => 'inicio_sesion');
?>
  1. <?php
  2. $this->Auth->loginAction = array('admin' => false, 'controller' => 'miembros', 'action' => 'inicio_sesion');
  3. ?>

5.2.6.5 loginRedirect

El componente AuthComponent recuerda qué par controlador/acción estabas tratando de ejecutar antes de que pedirte que te autenticaras, almacenando el valor en Session bajo la clave Auth.redirect. Sin embargo, si este valor de la sesión no está definido (si vienes de la página de login de un enlace externo, por ejemplo), entonces el usuario será redirigido a la URL indicada en loginRedirect.

Ejemplo:

<?php
    $this->Auth->loginRedirect = array('controller' => 'miembros', 'action' => 'inicio');
?>
  1. <?php
  2. $this->Auth->loginRedirect = array('controller' => 'miembros', 'action' => 'inicio');
  3. ?>

5.2.6.6 logoutRedirect

Puedes especificar a donde ira el usuario luego de 'deautenticarse', el inicio por defecto es la accion login

<?php
    $this->Auth->logoutRedirect = array(Configure::read('Routing.admin') => false, 'controller' => 'members', 'action' => 'logout');
?>
  1. <?php
  2. $this->Auth->logoutRedirect = array(Configure::read('Routing.admin') => false, 'controller' => 'members', 'action' => 'logout');
  3. ?>

5.2.6.7 loginError

Cambia el mensaje de error por defecto que se mostrará, cuando el login no sea exitoso.

<?php
    $this->Auth->loginError = "No, you fool!  That's not the right password!";
?>
  1. <?php
  2. $this->Auth->loginError = "No, you fool! That's not the right password!";
  3. ?>

5.2.6.8 authError

Cambia el mensaje de error por defecto que será mostrado, cuando intenten acceder a un objeto o a una acción a la que no autorizada.

<?php
    $this->Auth->authError = "Sorry, you are lacking access.";
?>
  1. <?php
  2. $this->Auth->authError = "Sorry, you are lacking access.";
  3. ?>

5.2.6.9 autoRedirect

Todavia no hay una traducion de este texto. Por favor ayudanos y traducirla.. Mas info sobre traduciones

Normally, the AuthComponent will automatically redirect you as soon as it authenticates. Sometimes you want to do some more checking before you redirect users:

<?php
	function beforeFilter() {
		...
		$this->Auth->autoRedirect = false;
	}

	...

	function login() {
	//-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).
		if ($this->Auth->user()) {
			if (!empty($this->data['User']['remember_me'])) {
				$cookie = array();
				$cookie['username'] = $this->data['User']['username'];
				$cookie['password'] = $this->data['User']['password'];
				$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
				unset($this->data['User']['remember_me']);
			}
			$this->redirect($this->Auth->redirect());
		}
		if (empty($this->data)) {
			$cookie = $this->Cookie->read('Auth.User');
			if (!is_null($cookie)) {
				if ($this->Auth->login($cookie)) {
					//  Clear auth message, just in case we use it.
					$this->Session->del('Message.auth');
					$this->redirect($this->Auth->redirect());
				}
			}
		}
    }
?>
  1. <?php
  2. function beforeFilter() {
  3. ...
  4. $this->Auth->autoRedirect = false;
  5. }
  6. ...
  7. function login() {
  8. //-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).
  9. if ($this->Auth->user()) {
  10. if (!empty($this->data['User']['remember_me'])) {
  11. $cookie = array();
  12. $cookie['username'] = $this->data['User']['username'];
  13. $cookie['password'] = $this->data['User']['password'];
  14. $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
  15. unset($this->data['User']['remember_me']);
  16. }
  17. $this->redirect($this->Auth->redirect());
  18. }
  19. if (empty($this->data)) {
  20. $cookie = $this->Cookie->read('Auth.User');
  21. if (!is_null($cookie)) {
  22. if ($this->Auth->login($cookie)) {
  23. // Clear auth message, just in case we use it.
  24. $this->Session->del('Message.auth');
  25. $this->redirect($this->Auth->redirect());
  26. }
  27. }
  28. }
  29. }
  30. ?>

The code in the login function will not execute unless you set $autoRedirect to false in a beforeFilter. The code present in the login function will only execute after authentication was attempted. This is the best place to determine whether or not a successful login occurred by the AuthComponent (should you desire to log the last successful login timestamp, etc.).

With autoRedirect set to false, you can also inject additional code such as keeping track of the last successful login timestamp

<?php
	function login() { 
		if( !(empty($this->data)) && $this->Auth->user() ){
			$this->User->id = $this->Auth->user('id');
			$this->User->saveField('last_login', date('Y-m-d H:i:s') );
			$this->redirect($this->Auth->redirect());
		}
	}
?>
  1. <?php
  2. function login() {
  3. if( !(empty($this->data)) && $this->Auth->user() ){
  4. $this->User->id = $this->Auth->user('id');
  5. $this->User->saveField('last_login', date('Y-m-d H:i:s') );
  6. $this->redirect($this->Auth->redirect());
  7. }
  8. }
  9. ?>

5.2.6.10 authorize

Todavia no hay una traducion de este texto. Por favor ayudanos y traducirla.. Mas info sobre traduciones

Normally, the AuthComponent will attempt to verify that the login credentials you've entered are accurate by comparing them to what's been stored in your user model. However, there are times where you might want to do some additional work in determining proper credentials. By setting this variable to one of several different values, you can do different things. Here are some of the more common ones you might want to use.

<?php
    $this->Auth->authorize = 'controller';
?>
  1. <?php
  2. $this->Auth->authorize = 'controller';
  3. ?>

When authorize is set to 'controller', you'll need to add a method called isAuthorized() to your controller. This method allows you to do some more authentication checks and then return either true or false.

<?php
    function isAuthorized() {
        if ($this->action == 'delete') {
            if ($this->Auth->user('role') == 'admin') {
                return true;
            } 
        }
	if ($this->action == 'view') {           
                return true;         
        }
	...
        return false;
    }
?>

  1. <?php
  2. function isAuthorized() {
  3. if ($this->action == 'delete') {
  4. if ($this->Auth->user('role') == 'admin') {
  5. return true;
  6. }
  7. }
  8. if ($this->action == 'view') {
  9. return true;
  10. }
  11. ...
  12. return false;
  13. }
  14. ?>

Remember that this method will be checked after you have already passed the basic authentication check against the user model.

<?php
    $this->Auth->authorize = 'model';
?>
  1. <?php
  2. $this->Auth->authorize = 'model';
  3. ?>

Don't want to add anything to your controller and might be using ACO's? You can get the AuthComponent to call a method in your user model called isAuthorized() to do the same sort of thing:

<?php
    class User extends AppModel {
        ...

        function isAuthorized($user, $controller, $action) {

            switch ($action) {
                case 'default':
                    return false;
                    break;
                case 'delete':
                    if ($user['User']['role'] == 'admin') {
                        return true;
                    }
                    break;
            }
        }
    }
?>
  1. <?php
  2. class User extends AppModel {
  3. ...
  4. function isAuthorized($user, $controller, $action) {
  5. switch ($action) {
  6. case 'default':
  7. return false;
  8. break;
  9. case 'delete':
  10. if ($user['User']['role'] == 'admin') {
  11. return true;
  12. }
  13. break;
  14. }
  15. }
  16. }
  17. ?>

Lastly, you can use authorize with actions such as below

<?php
    $this->Auth->authorize = 'actions';
?>
  1. <?php
  2. $this->Auth->authorize = 'actions';
  3. ?>

By using actions, Auth will make use of ACL and check with AclComponent::check(). An isAuthorized function is not needed.

<?php
    $this->Auth->authorize = 'crud';
?>
  1. <?php
  2. $this->Auth->authorize = 'crud';
  3. ?>

By using crud, Auth will make use of ACL and check with AclComponent::check(). Actions should be mapped to CRUD (see mapActions).

5.2.6.11 sessionKey

Todavia no hay una traducion de este texto. Por favor ayudanos y traducirla.. Mas info sobre traduciones

Name of the session array key where the record of the current authed user is stored.

Defaults to "Auth", so if unspecified, the record is stored in "Auth.{$userModel name}".

<?php
    $this->Auth->sessionKey = 'Authorized';
?>
  1. <?php
  2. $this->Auth->sessionKey = 'Authorized';
  3. ?>

5.2.6.12 ajaxLogin

Todavia no hay una traducion de este texto. Por favor ayudanos y traducirla.. Mas info sobre traduciones

If you are doing Ajax or Javascript based requests that require authenticated sessions, set this variable to the name of a view element you would like to be rendered and returned when you have an invalid or expired session.

As with any part of CakePHP, be sure to take a look at AuthComponent class for a more in-depth look at the AuthComponent.

5.2.6.13 authenticate

Todavia no hay una traducion de este texto. Por favor ayudanos y traducirla.. Mas info sobre traduciones

This variable holds a reference to the object responsible for hashing passwords if it is necessary to change/override the default password hashing mechanism. See Changing the Encryption Type for more info.

5.2.6.14 actionPath

Todavia no hay una traducion de este texto. Por favor ayudanos y traducirla.. Mas info sobre traduciones

If using action-based access control, this defines how the paths to action ACO nodes is computed. If, for example, all controller nodes are nested under an ACO node named 'Controllers', $actionPath should be set to 'Controllers/'.