I'm experiencing this weird problem with CakePHP 3. I wrote a rather normal login code for my app but for some reason, after successfully logging in, the app redirects me back to the login page.
Looks like the AuthComponent can't register my login session so the app wouldn't know if I'm logged in, so it brings me back to the login page.
Here is some code
Api/UsersController.php Login Method
public function login()
{
$this->checkPostRequest();
$email = trim(filter_var($this->request->data('email'), FILTER_SANITIZE_EMAIL) ?? '');
$password = trim($this->request->data('password') ?? '');
$hasher = new DefaultPasswordHasher;
if (empty($email) || empty($password)) {
throw new BadRequestException('You must provide an email address and password');
return false;
}
// Find user by email
$this->loadModel('Users');
$user = $this->Users->find('active')
->where([
'email' => $email
])
->first();
if ($user === null) {
throw new UnauthorizedException('Your email address or password is incorrect');
return false;
} else {
if ($hasher->check($password, $user->password) === false) {
// Record failed login attempt
$user->recordFailedLogin();
$this->Users->save($user);
throw new UnauthorizedException('Your email address or password is incorrect');
return false;
} else {
// Record successful login attempt
$user->recordSuccessfulLogin();
$this->Users->save($user);
// Set user as authenticated
$this->Auth->setUser($user->toArray());
$this->set([
'success' => true,
'user' => $user->toArray(),
'url' => $this->Auth->redirectUrl()
]);
}
}
}
login.js that makes an AJAX call to the UsersController API's login method:
that.$http.post('/api/users/login.json', {
email: that.emailInput,
password: that.passwordInput
})
.then((response) => {
response = response.body;
if (response.success === true) {
that.signingIn = true;
that.successful = true;
window.location.replace(response.url);
} else {
that.successful = false;
$(that.$el).find('form').form('add errors', [
response.message
]);
}
}, (response) => {
// error
});
Some additional details:
- All validations work correctly.
- The app does recognize a successful login, it just doesn't write any session or cookies for that.
Any advice would be much appreciated!