Laravel Ajax Login Tries To Redirect - ajax

I am trying to remove default Laravel behavior of redirected authenticated user once authenticated.
I commented in LoginController.php
//protected $redirectTo = '/home';
And also changed the AuthenticatesUsers vendor file to return JSON instead of a redirect on login success:
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
/*return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());*/
return response()->json(['SUCCESS' => 'AUTHENTICATED'], 200);
}
But still when I successfully login I see in my Chrome network tab that I get an error, because it is trying to redirect me to /home which is an undefined route, leading to the error and halting my Laravel SPA.
Why is Laravel continuing to direct me to /home even after I comment it out and change the Vendor files?

It was a middleware problem.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
//return redirect('/home');
}
return $next($request);
}
In, app/Http/Middleware/RedirectIfAuthenticated.php

Related

Laravel 6.x. Problem is Login Page, When I'm Creating Panels

Laravel 6.x. Now Problem is the First-time Login successfully working fine It redirects to the site where I need to be but second or more time login failed It redirect to the login page. Why?
In RedirectIfAuthenticated file
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
In RouteServiceProvider file
public const HOME = '/index/dashboard/';
In HomeController file
public function index()
{
if ((Auth::user())->user_role == 'admin')
{
$title='admin dashboard';
return view('admin-dashboard',compact('title'));
}
else{
return view('login-page');
}
}
I can not tell you for sure without more details. but one thing you can check is that you have set the right redirect url in the RedirectIfAuthenticated middleware.

Laravel: middleware check if user is softdeleted or not

I am using softdelete for users when a user is deleted.
When logging in or authenticating, all users are authenticated. So, I made a middleware named:
isSoftdeletedorNot
public function handle($request, Closure $next)
{
if ($request->user()->deleted_at == null) :
return $next($request);
else:
Auth::logout();
Session::flush();
Session::regenerate();
return redirect()->route('login')->withErrors(['suspended' => 'Your account is deactivated']);
endif;
}
It executes well. The problem is the redirected route shows 404 error and when I manually hard refresh it, it works again.
Try this
public function handle($request, Closure $next)
{
if ($request->user()->deleted_at != null) {
Auth::logout();
Session::flush();
Session::regenerate();
return redirect()->route('login')->withErrors(['suspended' => 'Your account is deactivated']);
}else{
return $next($request);
}
}

Custom Auth Middleware not redirecting properly for unauthorized user

I have created a custom auth controller for recognising unauthorized user and redirect them to login path. If logged in the middlewre is working absolutely fine, but showing error if not logged in. Here is my code
Middleware:
class CheckUserAuthenticated
{
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
return redirect('login'); // this code is not working
}
}
Error:
try this hope it help
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
return redirect('/login'); OR return redirect(route('login'));
}
class CheckUserAuthenticated
{
public function handle($request, Closure $next)
{
if(auth()->check()) {
$user_id = auth()->user()->id;
define('authenticated_user_id' ,$user_id);
return $next($request);
}
// return redirect('login'); // this code is not working
return redirect()->guest('/login');
}
}
redirect()->guest() will redirect if there is no authenticated user.
Example: If an authenticated user is logged in, it won't redirect them as they aren't a guest. If a user isn't logged in, the redirect will happen.
The issue is in circular routing, you are calling from one route, and then return to the same route from the middleware, so your request never reaches the endpoint.
if you call middleware on the...
Route::get('login')->middleware('auth);
...then middleware can not route to 'login' on the fail...
return redirect('login');
... because it will create the loop that never ends. The middleware should reroute to something else, or be placed on other route like 'admin'...
You probably have the middleware on the 'login', that creates the loop, just remove it.

Conditionally set a URL to redirect to after authentication

In my app, a post author can set an otherwise public post to private. If an unauthenticated user tries to visit that post, they will be prompted to login.
After they authenticate, I want to redirect them back to the original post URL, so they can read that private post.
This behavior is normally handled by Laravel's default auth middleware. However, because the posts are often public, I can't use that in this case.
Here's my current, non-functioning middleware:
public function handle($request, Closure $next)
{
$post = $request->route('post');
if ($post->isPrivate()) {
$request->session()->setPreviousUrl($request->url());
return redirect()->guest('login');
}
return $next($request);
}
My hope is that I can set a custom URL to redirect to (/posts/{id}). However, when I try to login, I'm redirected to my default $redirectTo property (/dashboard).
Is this something that's feasible? Am I even thinking about this in the correct way?
#adam, thanks for the assist!
For anyone else looking, here's my final code:
Middleware:
public function handle($request, Closure $next)
{
if (auth()->check()) {
return $next($request);
}
$post = $request->route('post');
if ($post->isPrivate()) {
$request->session()->setPreviousUrl($request->path());
return redirect()->guest('login');
}
return $next($request);
}
LoginController:
protected function authenticated(Request $request, $user)
{
if ($request->session()->has('url.intended')) {
return redirect($request->session()->get('url.intended'));
}
}

Role-based routing in LoginController (Auth)

In my Laravel 5.3 setup, I am using Bouncer package, and I defined two roles, admin and customer. When logged in, customers are redirected to /home, as specified in protected $redirectTo = '/home'; under App\Http\Controllers\Auth\LoginController.php. Now, if a user with the role of an admin logs in, he is also redirected to /home because $redirectTo does not make any distinction between user roles. My goal here is to redirect admin users to /admin/home instead.
What is the best solution to handle this? Here is my attempt.
In web.php routes, outside of any middleware groups:
Route::get('/home', function(Illuminate\Http\Request $request) { // http://myapp.dev/home
if (Auth::user()->isA('customer')) // -> goto HomeController#index
return app()->make('\App\Http\Controllers\HomeController')->index($request);
else if (Auth::user()->isAn('admin')) // -> redirect
return redirect('/admin/home');
else
abort(403);
})->middleware('auth');
Route::group(['prefix' => 'admin','middleware' => 'auth'], function () {
Route::get('/home', 'Admin\HomeController#index');
});
Alternatively, this can can be done in a middleware, as well:
Route::get('/home', 'HomeController#index')->middleware('auth', 'role');
// in VerifyRole.php middleware...
public function handle($request, Closure $next, $guard = null)
{
if (Auth::user()->isAn('admin')) {
return redirect('/admin/home');
}
return $next($request);
}
This would work, but it's not scalable if more roles are added. I am sure there must be an elegant built-in way to accomplish this. So the question is, how do I route users to their proper dashboard (i.e. home) based on their role?
You can override the authenticated() method in your class App\Http\Controllers\Auth\LoginController as:
protected function authenticated(Request $request, $user)
{
if ($user->isA('customer'))
return redirect('/home');
else if ($user->isAn('admin'))
return redirect('/admin/home');
}
Or
You can override the redirectPath() method as:
public function redirectPath()
{
if (auth()->user()->isA('customer'))
return '/home';
else if (auth()->user()->isAn('admin'))
return '/admin/home';
}
In Laravel 5.3, you can override sendLoginResponse() method in AuthController.php to be able to redirect users to a different routes after login.

Resources