How to restrict saving of data in db for user when the admin deactivated it in cakephp3.x?

35 Views Asked by At

I need a solution where I can restrict the user to save any data when he is been deactivated by the admin. Suppose the user is active on a page where he is going to save a form but at the same instance admin has deactivated him. so , now when he try to save the form , he should be redirected to the login page saying "Your account is been deactivated, contact the support", without saving the data. I am working in cakephp 3.x . I tried to use beforeFilter for it. But it is deactivating the user but also the user is able to save the data.

1

There are 1 best solutions below

0
Zenzs On

I had a similar situation. I added a custom finder to the auth component to restrict deactivated users from making requests when they were deactivated but it only stopped deactivated users from logging in and NOT immediately restricting them from making any request. This meant a deactivated user could still access the application for the remainder of their session. (A lot of havoc can be caused by a disgruntled deactivated employee in say 10 hours.)

My solution was to tell the auth component to use controller hook methods for authorization. Cookbook info here

App Controller - Initialize action - Auth Component

$this->loadComponent('Auth', [
    'authorize' => 'Controller', // ADDED THIS LINE
    'authenticate' => [
        'Form' => [
            'finder' => 'active' // Custom finder to retrieve details for login of active users - for login only.
            ]
        ],

        // Other auth component actions here
]);

And this is what logs the user out immediately

App Controller - isAuthorized

public function isAuthorized()
{
    if ($this->checkActiveAndRole() === true) {
        return true;
    } 
    return false;    
}

App Controller - checkActiveAndRole - (Streamlined for this post)

private function checkActiveAndRole()
{

    // Initialise and validate the id from auth component.
    $id = $this->Auth->user('id');

    // Select the users status and role.
    $Users = TableRegistry::getTableLocator()->get('Users');    
    $query = $Users->find('statusRole', [
        'id' => $id
    ]);

    if ($query->isEmpty()) {
        return false;
    }

    $status = 0;      
    foreach ($query as $row): 
        $status = $row->status;
    endforeach; 

    // Check if the user is active.
    if ($status === 0) {            
        return false;                
    }
    return true;               
}

And this worked for me. Ie: Checking if the user is active on every request with the isAuthorized() function in the app controller