I have a controller that manages the authentication, but when creating the middleware, I get the error ERR_TOO_MANY_REDIRECTS
, if I leave the middleware alone, it return $next($request);
follows the normal flow of the program, but the middleware does not obviously do the validations.
It is worth mentioning that I send the form inputs by ajax to the controller directly, I don't know if it has something to do with it, but I am attaching that part of the code anyway.
ajax-request
<script !src="">
$(document).on('click', '#login', function (e) {
/* EVITAR EVENTO DEFAULT DEL BOTON */
e.preventDefault();
let email = $('#email').val();
// alert(email);
let password = $('#password').val();
// alert(password);
$.ajax({
url : '{{url('admin/auth')}}',
method : 'post',
data : {
_token : '{{csrf_token()}}',
email : email,
password: password
},
success: (data) => {
console.log(data);
if (data !== 'Éxito') {
toastr.options = {
'closeButton' : false,
'debug' : false,
'newestOnTop' : false,
'progressBar' : false,
'positionClass' : 'toast-top-right',
'preventDuplicates': false,
'onclick' : null,
'showDuration' : '300',
'hideDuration' : '1000',
'timeOut' : '5000',
'extendedTimeOut' : '1000',
'showEasing' : 'swing',
'hideEasing' : 'linear',
'showMethod' : 'fadeIn',
'hideMethod' : 'fadeOut'
};
toastr.error(data);
} else if (data === 'Éxito') {
toastr.options = {
'closeButton' : false,
'debug' : false,
'newestOnTop' : false,
'progressBar' : false,
'positionClass' : 'toast-top-right',
'preventDuplicates': false,
'onclick' : null,
'showDuration' : '300',
'hideDuration' : '1000',
'timeOut' : '5000',
'extendedTimeOut' : '1000',
'showEasing' : 'swing',
'hideEasing' : 'linear',
'showMethod' : 'fadeIn',
'hideMethod' : 'fadeOut'
};
toastr.success(data);
setTimeout(() => {
window.location = '{{route('admin.dashboard')}}';
}, 1500);
{{--window.location = '{{url('admin/dashboard')}}';--}}
}
}
});
});
</script>
Authentication Controller
public function index(Request $request) {
return view('backend.auth', [
'title' => 'Login',
'description' => 'Login del backend del sistema del Ingeniero David Paucar'
]);
}
public function authentication(Request $request) {
$validator = \Validator::make($request->all(), [
'email' => ['required', 'email'],
'password' => ['required', 'min:6']
], $messages = [
'email.required' => 'El :attribute es obligatorio',
'password.required' => 'La :attribute es obligatoria',
'email' => 'El :attribute debe ser un :attribute válido',
'min' => 'La :attribute debe tener al menos 6 caracteres'
], [
'password' => 'contraseña'
]);
$error = $validator->errors();
$userInfo = Admin::where('email', '=', $request->email)->first();
if ($error) {
foreach ($error->all() as $message) {
return $message;
}
if (!$userInfo) {
return 'Las credenciales ingresadas no coinciden con los registrados';
} else {
if (Hash::check($request->password, $userInfo->password)) {
$request->session()->put('LoggedUser', $userInfo->email);
return 'Éxito';
}
}
}
}
public function dashboard() {
$data = [
'LoggedUser' => Admin::where('email', '=', session('LoggedUser'))->first(),
'title' => 'Dashboard'
];
return view('backend.dashboard', $data);
}
public function exit(Request $request) {
Auth::logout();
$request->session()->flush();
return route('admin');
}
Middleware
If I have it in the following way the error happensERR_TOO_MANY_REDIRECTS
public function handle(Request $request, Closure $next) {
if (!session()->has('LoggedUser')) {
return redirect('admin');
}
if (session()->has('LoggedUser')) {
return back();
}
return $next($request);
}
But if I leave it as follows, the flow of the program continues, but obviously because it has no validation.
public function handle(Request $request, Closure $next) {
return $next($request);
}
Routes
Finally I attach my routes that I think are simple but the problem that it generates for me I cannot find why.
Route::post('admin/auth', [AuthController::class, 'authentication'])->name('admin.auth');
Route::group(['middleware' => 'admin'], function () {
Route::get('admin', [AuthController::class, 'index']);
Route::get('admin/dashboard', [AuthController::class, 'dashboard'])->name('admin.dashboard');
});
Route::get('admin/exit', [AuthController::class, 'exit'])->name('admin.exit');
I was able to solve it by adding
withoutMiddleware
to my route that manages the ajax requests that manages the authentication to the controller, I guess I had the error since the route is grouped and the middleware is executed globally.