Display a msg when a user authenticates more than 5 times a day with cakephp 3.x or 4

45 views Asked by At

I want to know if a user has logged in 5 times or more in the same day and show him a msg afterwards this is my login function:

public function login()
    {
        if($this->request->is('post')){
            $user = $this->Auth->identify();
            if($user){
               $this->Auth->setUser($user);               
                //return $this->redirect(['controller' => 'posts']);
                return $this->redirect(['controller' => 'users']);
               }
            
            // Bad login
            $this->Flash->error('Incorrect login.');
        }
    }

any ideas, please?

i already tried this to know if a user is logged in or not but i didn't know how i could go from here to my knowing how many times a user login in a day.

class AppController {
    // ....
     function beforeFilter(){
       ....
       $this->set('auth',$this->Auth);
     }
     //....
   }

in the view:

  if( $this->Auth->User('id') ) {
    // user is logged
  }
1

There are 1 answers

0
Salines On

Your request is resolved by creating a cache file with a unique identifier, e.g. email plus date, during user authentication.

Every time the user authenticates, you need to increase the value in the cache by one.

Next, somewhere in your app you read that cache, if the value is 5 or higher you create a message.

public function login()
{
    $loginAttempts = Cache::read(date('Ymd') . '_' . $email, 'loginAttempts');

    if ($this->request->is('post') && $loginAttempts >= 5) {
        $this->Flash->error('... your msg);
    }
   if($this->request->is('post')){
        $user = $this->Auth->identify();
        if($user){
           $this->Auth->setUser($user);

            $i = $loginAttempts + 1;
            Cache::write(date('Ymd') . '_' . $email, $i, 'loginAttempts');

          
            //return $this->redirect(['controller' => 'posts']);
            return $this->redirect(['controller' => 'users']);
           }
        
        // Bad login
        $this->Flash->error('Incorrect login.');
    }
}