S raju
S raju

Reputation: 49

How can we provide authentication in CakePHP?

I am learning CakePHP. In the controller, I have written a program like this. I also created a form on the login page. But it's showing an error for $this->Auth->login();.

If I give it like this in CakePHP, it's showing this error:

Error: Call to a member function login() on a non-object
File: C:\wamp\www\cakephp\app\Controller\UsersController.php
Line: 20

UserController.php

public function login() {
    $this->Auth->authenticate = array('Form');
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirect());
        }
        $this->Session->setFlash(__('Invalid username or password. Try again.'));
    }
}

Upvotes: 1

Views: 132

Answers (1)

karmicdice
karmicdice

Reputation: 1061

Add this to your AppController.php

class AppController extends Controller {
    public $components = array(
                    'Auth' => array(
                    'loginAction' => array('controller'=>'User', 'action'=>'login'),
            'loginRedirect' => array('contoller'=>'User', 'action'=>'login'),
            'logoutRedirect' => array('controller'=>'User', 'action'=>'logout'),
            'authenticate' => array(
                'Form' => array(
                    'userModel' => 'User',
                    'fields' => array(
                        'username' => 'email',
                        'password'=>'password'
                    )))));

And this in UserController.php

public function beforeFilter(){
            parent::beforeFilter();
            $this->Auth->allow('login');
        }

And this in app/Model/User.php

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

Upvotes: 1

Related Questions