Redirect if authenticated in Laravel 5.3 - laravel

I'm using the Auth scaffold in Laravel 5.3 and I've changed the routes for the auth. So instead of /login and /register I use /signin and /signup.
In Laravel 5.2 we had this by default in the auth middleware,
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
}
return redirect()->guest('login');
}
return $next($request);
}
This would redirect to the login route if the user wasn't logged in. In Laravel 5.3 we have this,
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
This redirects an already logged in user to the default route /. So they switched it around in 5.3. Instead of defining where guest go, we define were logged in users go.
My question is, how would I natively to Laravel 5.3 change were guests go?
Because at the moment, people who try to access sites protected by the middleware automatically end up at a /login route. I would like to change this to /signin but I can't find anywhere to customize this behaviour.
Any ideas?

how would I "natively" to Laravel 5.3 change were guests go?
Looks like there's a new unauthenticated() method in app/Exceptions/Handler.php which handles unauthenticated users and redirects to login.
As this is part of your app, no reason you couldn't customize it to redirect elsewhere.

You can try this in the app.blade.php with JS:
#if (Auth::guest())
<script type="text/javascript"> window.location = "{{url('/login')}}"; </script>
#endif

Related

Auth::check fails in middleware

Can somebody explain why this strange behavior of Laravel is happening? Basically, I am trying to create a middleware for my application
public function handle(Request $request, Closure $next)
{
if (auth()->check()) {
$expires = Carbon::now()->addMinute(2);
\Illuminate\Support\Facades\Cache::put('user-is-online-' . Auth::user()->id, true, $expires);
}
return $next($request);
}
}
But auth()->check it is keep failing and not returning true , (user is authenticated) , auth()->check is working in other places like web routes and controllers method but why not here ?
If you are using auth middleware to protect your routes, then make sure this auth middleware is set to run before your middleware, otherwise auth()->check() will return false. Try php artisan route:list and check the orders of middlewares for your specified route.

Laravel Custom Middleware

I am trying to achieve this using middleware
web.php
Route::get('/test', 'TestController#index')->middleware('TestLogin');
redirect to /test if session is found
Route::get('/test1', 'TestController#index1')->middleware('TestLogin');
redirect to test1 if session is set
Middleware -TestLogin
public function handle($request, Closure $next)`
{
if($request->session()->get('Username'))
{
return redirect()->route(\);
// what to write here to redirect to the path its being called from
}
return redirect()->route('login');
}
don't want to use default auth middleware
Your middleware is suppose to check the login (session), if it is not found then redirect to login page otherwise it should pass the request. Something like this:
public function handle($request, Closure $next)
{
// No login session, redirect
if(!$request->session()->get('Username'))
{
return redirect()->route('login');
}
// Pass the request down the rest of pipeline
return $next($request);
}
You should consider to use built in authentication system in Laravel itself, it will save you lots of code and you can be sure the auth is handled correctly in security point of view.

Where to change route '/home' when user is login and try to login again in laravel

I just want to know where are the Auth routes defined.
In my case I am logged In but for testing purpose try to go to login page agian using
localhost/login
this should take me to my dashboard or profile but it redirects to '/home' and unable to found this view.
How to configure this route and where to configure this in laravel.
In RedirectIfAuthenticated in the App\Http\Middleware folder:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
So change the redirect('/home'); to where ever you want it to redirect.
The code that defines the route to redirect after a successful login.
app/Http/Controllers/Auth/LoginController.php
protected $redirectTo = '/home';
The code that redirects a logged in user if they try to visit a guest page.
app/Http/Middleware/RedirectIfAuthenticated.php
return redirect('/home');
The code that redirects a user to the login page when an unauthenticated user tries to open a page that needs authentication.
app/Exceptions/Handler.php
return redirect()->guest(route('login'));
In Laravel 6 and above.
Just go to app/Providers/RouteServiceProvider.php
and change
public const HOME = '/home'
to
public const HOME = '/new-name'

Laravel Ajax Login Tries To Redirect

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

Laravel 5.2 Redirect admin page after login as admin

Laravel 5.2 has been out for some time now. Yes, it has new auth function which is very good. Specially for beginners.
My question,
How to check if user is admin and then redirect safely to admin/dashboard properly? I know one way is to use admin flag in database but can any of you show some example?
go to AuthController.php and add this method
where role is the user role as defined in the database.
protected function authenticated($request,$user){
if($user->role === 'admin'){
return redirect()->intended('admin'); //redirect to admin panel
}
return redirect()->intended('/'); //redirect to standard user homepage
}
As in Laravel 5.3 / 5.4
Add following line to create_users_table migration.
$table->boolean('is_admin');
Add following method to LoginController.
protected function authenticated(Request $request, $user)
{
if ( $user->is_admin ) {
return redirect('/admin/home');
}
return redirect('/home');
}
Additional note don't forget to add the following lines to RedirectIfAuthenticated middleware:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
// the following 3 lines
if (Auth::user()->is_admin) {
return redirect('/admin/home');
}
return redirect('/home');
}
return $next($request);
}
Otherwise if you e.g. type yourdomain/login and your logged in as admin it would be redirected to home instead of admin/home.
AuthController extends the AuthenticatesAndRegistersUsers trait, which has a public method named redirectPath. In my case I would extend that method on the AuthController and I'd put my logic there:
public function redirectPath()
{
if (Auth::user->myMethodToCheckIfUserHasAnAdminRoleLikeAnEmailOrSomethingLikeThat()) {
redirect('admin/dashboard');
}
redirect('home');
}
in Auth/LoginController there is protected $redirectTo = '/home';
change '/home' to '/loginin' for example, and create a new controller and in the controller get the information of the user and check if he is a admin or not and then redirect him to the proper page

Resources