Monday, August 3, 2015

cakephp3 : implementing auth using custom controller and model

I was trying to implement auth in a plugin that I created.

Lets suppose there is a controller name Team, in which there are few functions like login() logout() index() apart from other crud functions.

Following is the sample code of team controller

    namespace Team\Controller;

    use Team\Controller\AppController;
    use Cake\Event\Event;
    use Cake\Network\Exception\NotFoundException;
    class TeamsController extends AppController {

    
     
     public function beforeFilter(\Cake\Event\Event $event)
{
$this->Auth->allow(['login','logout']);
}
     
    public function index()
    {
        $this->paginate = [
            'contain' => ['TeamRoles']
        ];
        $this->set('teams', $this->paginate($this->Teams));
        $this->set('_serialize', ['teams']);
    }
    public function login()
{
$this->layout = 'logindefault';
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}

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

Above code is working fine, if i directly go to the login url.
But If i am trying to go to index page. It redirects me to the users controller login function which for obvious reason don't exist.

Following is my app controller code.

    namespace Team\Controller;
    use App\Controller\AppController as BaseController;
    use Cake\Event\Event;
    class AppController extends BaseController {
        public $components = array(
'Auth' => array(
'loginRedirect' => array(
'controller' => 'Teams',
'action' => 'index'
),

'logoutRedirect' => array(
'controller' => 'Teams',
'action' => 'login'
),

'authenticate' => array(
   'Form' => array(
       
       'userModel' => 'Teams'
   )
),      
)
);
    public function isAuthorized($user)
{
return false;
}

        public function initialize() {
         $this->loadComponent('Flash');
        }
        
    }
Kindly let me know, what have I missed??

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: