Cakephp Auth Component Does Not Work Properly

Asked

Viewed 798 times

2

I am making a user registration screen. When the user completes the registration, it is redirected to a restricted area. On this same screen, there is a login and password field for them to log in. However, the only thing that works is the registration, but even so, is not redirecting to the restricted area. My codes are like this:

Appcontroller:

class AppController extends Controller {

public $components = array('Auth');

function beforeFilter() {
    $this->Auth->fields = array(
        'username' => 'username',
        'password' => 'password'
    );

    $this->Auth->loginAction = array(
        'controller' => 'users',
        'action' => 'login'
    );
    $this->Auth->loginRedirect = array(
        'controller' => 'profiles',
        'action' => 'index'
    );
    $this->Auth->logoutRedirect = '/';

    $this->Auth->authError = 'Area Restrita! Efetue login!'; // Mensagem ao entrar em area restrita
    $this->Auth->loginError = 'Nome de usuario ou senha não conferem!'; // Mensagem quando não se autenticar
    $this->Auth->allow('pages', 'display');

}

}

Userscontroller:

class UsersController extends AppController {

public function register() {
    $this->loadModel('User');
    //$this->autoRender = FALSE;
    if ($this->request->is('post')) {
        $day = $this->request->data['day'];
        $mouth = $this->request->data['mouth'];
        $year = $this->request->data['year'];
        $birth = $year . "-" . $mouth . "-" . $day;
        $date = date('Y-m-d H:i:s');

        if ($this->User->save(array(
                    'name' => $this->request->data['name'],
                    'username' => $this->request->data['email1'],
                    'password' => $this->request->data['pass'],
                    'birthday' => $birth,
                    'sex' => $this->request->data['sex'],
                    'date_sign' => $date
                ))) {
            $this->Auth->loginRedirect(array('controller' => 'profiles', 'action' => 'index'));              
        }
    }
}

public function login() {
    //$this->redirect($this->Auth->redirect());   
    if ($this->Auth->login()) {
        $this->redirect($this->Auth->redirect());
    } else {
        $this->Session->setFlash(__('Usuário ou senha inválido'));
    }
}

function logout() {
    $this->redirect($this->Auth->logout());
}

}

User (Model):

App::uses('AuthComponent', 'Controller/Component');

class User extends AppModel {

public function beforeSave($options = array()) {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

}

And in the layout default.ctp, the form that makes the registration I am pointing to "users/Register" and the form for the login, I point to "users/login"

Can anyone tell me what might be wrong?

1 answer

1

Try it like this:

if ($this->User->save(array(
                'name' => $this->request->data['name'],
                'username' => $this->request->data['email1'],
                'password' => $this->request->data['pass'],
                'birthday' => $birth,
                'sex' => $this->request->data['sex'],
                'date_sign' => $date
            ))) {
        $this->Session->setFlash('O usuários foi salvo.');
        $this->redirect(array('controller' => 'profiles', 'action' => 'index'));              
    } else {
        $this->Session->setFlash('Erro no cadastro.');
}

For controller redirects always use $this->redirect().

Function Login in Userscontroller:

public function login() {
//Verifica o tipo de requisição.
if ($this->request->is('post')) {  
    if ($this->Auth->login()) {
        $this->redirect($this->Auth->redirect());
    } else {
        $this->Session->setFlash(__('Usuário ou senha inválido'));
    }
}

}

  • Another thing, instead of creating a new array within save, change the $this->request->data array itself and use if/save just like this: if($this->User->save($this->request->data)) {...}, the code gets cleaner.

  • So it still doesn’t work, it doesn’t redirect to the restricted area, and it doesn’t log in

  • So you are not saving, you have checked if the new user appears in the database?

  • Have you tried following the blog tutorial on the Cake page? I highly recommend it before trying to create an application on your own. And beware of book and API versions, if it’s not the same as your cake package, it can be confusing.

  • Yes, I tried the tutorial and the user is saving, I checked in the bank, also gave permission in $this->Auth->allow()

  • So the version I’m using is the latest, downloaded right from the site

  • Try adding the flashes and see what he replies, I edited the answer.

  • So, I put your flash and gave no message, but I got the message Restricted Area! Login! that I had put on $this->Auth->authError

  • Check the answer again, what I believe is occurring is that you are not checking the type of request, when accessing the form, the request will always be 'get' and when posting the user and password, 'post', so after you enter and give Submit, it will perform the login function, with the data of the completed form. This perception of what is get/post/put/delete is very important in order to be able to guide the method in which way it should behave in each request.

  • Puts will not, I think there is something wrong with Appcontroller pq I changed the $this->Auth->loginAction by putting another controller and other action and did not change the url, always back p the users/login

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.