1
votes

Normally, in cakephp there is Auth component to help user login and there is function Auth->Allow() to make the guests users still can access to some pages like Index. But now i want that only Activated account can access almost every function of the web, but still except some normal pages like index, view etc. I have a fucntion in Appcontroller

public function is_activated(){
    $userId = $this->Auth->user('id');
    $user = $this->Users->find('all', [
            'conditions' => ['id' => $userId],
            'fields' => ['id', 'email', 'activated']
        ])->first();
    $activated = $user->activated;
    if($activated !== 1){
            $this->Flash->error(__('Your account is not yet activated'));
            return $this->redirect('/users/activate');
    }
}

I call it in BeforeFilter along with Auth->allow() in ProjectsController:

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    $this->Auth->allow(['index', 'getMyProjects']);
    $this->is_activated();
}

But in this way, every pages are affected and Auth->allow() not working anymore. Can anybody show me a better way for my is_activated() function, i guess that this way i redirect the web is not a good way.

1

1 Answers

1
votes

What you are looking for is isAuthorized() function:

public function isAuthorized($user){
    if($user->activated){
        return true;
    }
    return false;
}

Put it in your AppController, you can also override it in your other controllers. If present, it will be automatically called.

Further reading:

https://book.cakephp.org/3.0/en/tutorials-and-examples/blog-auth-example/auth.html#authorization-who-s-allowed-to-access-what

https://book.cakephp.org/3.0/en/controllers/components/authentication.html#authorization