Skip to content

Instantly share code, notes, and snippets.

@icaroscherma
Last active April 1, 2016 23:45
Show Gist options
  • Save icaroscherma/a3415b90f391a17168430dc575661360 to your computer and use it in GitHub Desktop.
Save icaroscherma/a3415b90f391a17168430dc575661360 to your computer and use it in GitHub Desktop.
CakePHP 3: Migrating from scope to finder (auth)
<?php
// src/Controller/AppController.php
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
],
// Older "scope" / "contain"
'finder' => 'auth'
]
]
]
);
// src/Model/Table/Users.php
public function findAuth(\Cake\ORM\Query $query, array $options)
{
$query
// ->select(['id', 'email', 'password'])
->where(['Users.active' => 1]);
return $query;
}
@icaroscherma
Copy link
Author

<?php
// add before (Auth->setUser())
                // Update Last login
                $userData = $this->Users->get($user['id']);
                $userData->lastlogin = \Cake\I18n\Time::now();
                $userData->dirty('modified', true); // Doesnt update the "modified" field
                $this->Users->save($userData);

@icaroscherma
Copy link
Author

<?php
<?php
public function login()
{
    if ($this->request->is('post')) {
        if (!$this->Users->findByUsername($this->request->data['username'])->count()) {
            $this->Flash->error(__('The username you provided does not belong to any registered account. Please correct the username.'), ['key' => 'auth']);
            // Redirect here
        }

        $user = $this->Auth->identify();
        if ($user) {
            if (!$user['verified']) {
                $this->Flash->error(__('Your account is not yet verified. Please check your email inbox to find the registration email we sent you.'), ['key' => 'auth']);
                // another redirect here
            }
            $this->Auth->setUser($user);
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('You have provided the wrong password. Please try again.'), ['key' => 'auth']);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment