i am learning codeigniter 4, i am trying to get the login page block once my user is logged but i am getting the error too many redirection and i dont know how to fix it
my login controller:
public function login()
{
$validated = $this->validate([
'email' => 'required|valid_email',
'password' => 'required',
],[
'email'=> [
'required' => 'E-mail required',
'valid_email' => 'E-mail not valid',
],
'password'=> [
'required'=> 'Password required',
]
]);
if (!$validated) {
return redirect()->route('login')->with('errors', $this->validator->getErrors());
} else {
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
}
$usersModel = new UsersModel();
$dataUser = $usersModel->getByEmail($email);
if (count($dataUser) > 0) {
$hashUser = $dataUser['users_password'];
if (password_verify($password, $hashUser)) {
unset($hashUser);
session()->set('isLoggedIn', true);
session()->set('nome', $dataUser['users_name']);
return redirect()->to(base_url('app/dashboard'));
}
}
}
public function logout()
{
session()->destroy();
return redirect()->to(base_url('login'));
}
my auth filter:
if ((bool)session()->isLoggedIn != true) {
return redirect()->to(base_url('login'));
}
and in the configs/filter i am adding in the filter globals
'before' => [
'auth'=> [
'except' => [
'login',
'/',
'search/*',
'post/*',
'sobre',
'contato'
]
]
the thing is, if i change the auth to check if has the session and remove the exception ‘login’ i get the error in my login and in my app/dashboard, what iam doing wrong here ?
i already tryit change the auth filter to check if exist the session but always give me the error too many redirections
2
Answers
You can just check if the session variables you create here exist. If they do you return an error. there are other ways but this is the siplest.
To fix this, you can modify your authentication filter to exclude the ‘login’ route only if the user is not logged in. Here’s how you can do it:
If it’s not work then try 2nd way
Add redirection in the login form page
I hope it works for you,
Thanks!