Prevent login to user and custom guards at the same time - laravel

I am using a custom guard for a different type of user using a custom guard labelled business_user.
I have noticed I am able to login to as both normal users (web) and my business_users.
I've read in the Pusher documentation that I used to create my custom guards in the first place to add additional middleware into my "LoginController".
But I don't actually even have a LoginController, I've created my own controllers for each user type. AuthController (for web) and BusinessController (for business_user).
I have created a third controller labelled LoginController with the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:business_user')->except('logout');
}
}
I also updated my RedirectIfAuthenticated as follows:
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "business_user" && Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
I also have a RedirectIfAuthenticated middleware inside my Middleware folder.
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "business_user" && Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
When I land on my user login page, it still allows me to attempt logging in. Can someone tell me how to resolve this?

In LoginController, you can override authenticated method.
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
auth()->login($user); // this method will login with default guard
return redirect()->intended($this->redirectPath());
}

I think because the order of middleware
<?php
public function __construct()
{
$this->middleware('guest')->except('logout'); // this procress first and redirect to login page
$this->middleware('guest:business_user')->except('logout');
}
So, I think you can check directly in __construct() of LoginController or in login view (blade file)
#if (Auth::check('business_user'))
You are already logged in (or perform a redirect somewhere)
#else
//display login form
#endif

Related

How to fix "Laravel redirect to the same login page" and middleware return false all time?

Work in the server (same code) but in localhost, it returns false always I have tried many ways.
I have tried Laravel build-in function login and so far the result always returns false while debugging.
//Middleware RedirectIfAdmin
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
$auth=Auth::guard('admin');
if (Auth::guard($guard)->check()) {
return redirect('admin/dashboard');
}
return $next($request);
}
}
I will add other code also if needed please tell me I am a new to ask question here. Please guide me.
Can you add the code from where you are calling the method handle?
namespace App\Http\Middleware;
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAdmin
{
public function handle($request, Closure $next, $guard = 'admin')
{
if (Auth::guard($guard)->check()) {
return redirect('admin/dashboard');
}
return $next($request);
}
}

laravel auth middleware not redirectly on intended page

I am using hesto/multi-auth package
as default if i have assigned the auth middleware to a route the so after login it should redirect me back to the intended page but it's doing only the first time..
everything working exactly i want only the first time but once i logout and try to access the route again it does go to login page and than redirects to the user/home, but first time it works perfect see the 40 sec video
http://neelnetworks.org/video/laravel.mp4
any solution for this?
these are my web routes
Route::get('/', 'PagesController#getIndex')->middleware('user');
Route::group(['prefix' => 'user'], function () {
Route::get('/login', 'UserAuth\LoginController#showLoginForm');
Route::post('/login', 'UserAuth\LoginController#login');
Route::post('/logout', 'UserAuth\LoginController#logout');
Route::get('/register', 'UserAuth\RegisterController#showRegistrationForm');
Route::post('/register', 'UserAuth\RegisterController#register');
Route::post('/password/email', 'UserAuth\ForgotPasswordController#sendResetLinkEmail');
Route::post('/password/reset', 'UserAuth\ResetPasswordController#reset');
Route::get('/password/reset', 'UserAuth\ForgotPasswordController#showLinkRequestForm');
Route::get('/password/reset/{token}', 'UserAuth\ResetPasswordController#showResetForm');
});
here is my Pages Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function getIndex()
{
return "hello";
}
}
first time it works perfectly why not after we logged in once?
it works again if i clear all my cache and cookies, is this a default behaviour or is this a bug in laravel? can you please clarify or is it a issue with the package
the issue has been raised in github https://github.com/Hesto/multi-auth/issues/46
Make your showLoginForm method like this inside your UserAuth/LoginController.php
public function showLoginForm()
{
session()->put('url.intended',url()->previous());
return view('user.auth.login');
}
Because it changes the previous url when posting form to /user/login and you will be redirected to /user/home if you logged in
after so much of digging i found out the correct solution
in RedirectIfNot{guard-name} eg RedirectIfNotAdmin
we need to add this line
session()->put('url.intended', url()->current());
so the middleware will look like this
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
session()->put('url.intended', url()->current());
return redirect('/admin/login');
}
return $next($request);
}
}
Default redirect for laravel after login is to go to /home set in the LoginController:
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
and there is default middleware RedirectIfAuthenticated
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
and in app/Http/Controllers/Auth/RegisterController.php
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
So that is where you need to make changes in order to work your way...

how to use session in middleware to always check that a user is logged in or not

i am new in laravel . i am trying to check if user is logged in or guest . i create a middleware named (checkUserLogin) and my code is:
namespace App\Http\Middleware;
use Auth;
use Closure;
use App\Http\Controllers\Controller;
use session;
class checkUserLogin
{
public function handle($request, Closure $next)
{
if (session()->get('email') != ''){
// redirected to dashboard.
}else{
// redirect to login page.
}
return $next($request);
}
}`
in my controller and blade template session()->get('email') works fine and i get the email of the user who logged in but in middleware if i try to print the session()->get('email') then a blank screen appears.
Use The Tools Given To You
Read the documentation and learn about Retrieving The Authenticated User. You will see that you can retrieve the logged in user with $request->user()
Look at the code for the included middleware RedirectIfAuthenticated. You will see that you can check if a user is logged in with Auth::guard($guard)->check()
Example Middleware Code
namespace App\Http\Middleware;
use Auth;
use Closure;
class checkUserLogin
{
public function handle($request, Closure $next)
{
if ( $request->user() ){
// user is logged in
} else {
// user is not logged in
}
return $next($request);
}
}
Some Thoughts
If your goal is for any visitor to see the route, but to show logged in visitors a different portion of content than you would show guests, this is simple to do within the Controller. For example, it is common to show a link to "Login" when the user is not logged in. When the user is logged in it is common to show the user account menu instead.
you can use this code.
Auth::user();
this will check automatically
just replace the below lines of code with yours... hope will work...
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class checkUserLogin
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $user;
/**
* Create a new middleware instance.
*
* #param Guard $user
* #return void
*/
public function __construct(Guard $user)
{
$this->user = $user;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->user->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('login');
}
}
return $next($request);
}
}

Laravel authenticated user logout error

tried to implement a simple user register/login function on my site using the laravel default controllers (auth/password), but as soon as I login, the class RedirectIfAuthenticated handle function prevents all access to auth url's, thus I cannot logout anymore. Is there a bug and I need to write an exception on the handle function or have I missed something?
Here is how the class looks like by default:
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
//dd($next($request));
if (Auth::guard($guard)->check()) {
return redirect('/articles');
}
return $next($request);
}
}
The AuthController's constructor should look similar to this:
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
The guest middleware is handled by the RedirectIfAuthenticated class and, in order to have the logout functionality working, you should choose one:
call the logout method from your AuthController.
call whichever method you use for logout and exclude it in AuthController's constructor:
public function __construct()
{
$this->middleware('guest', ['except' => '<whichever_method>']);
}
For potentially more-advanced reasons and needs, I will show a different idea.
Inside any middleware, a person could implement their own except list. Here is a reference:
<?php
namespace App\Http\Middleware;
use Closure;
class CustomThing
protected $except = [
'api/logout',
'api/refresh',
];
public function handle($request, Closure $next)
{
foreach ($this->except as $excluded_route) {
if ($request->path() === $excluded_route) {
\Log::debug("Skipping $excluded_route in this middleware...");
return $next($request);
}
}
\Log::debug('Doing middleware stuff... '. $request->url());
}
}
I will leave it up to imagination to extend that to support other types of URLs. For example, investigate matchers such as $request->url(), $request->fullUrl(), and $request->is('admin/*').
A person could investigate the vendor code for the VerifyCsrfToken middleware and make their custom one support something like this:
protected $except = [
'api/logout',
'api/refresh',
'foo/*',
'http://www.external.com/links',
];
If you want it to be a reuseable solution, make that matching algorithm a Trait and import it into any middleware you want to exclude routes from.

Controller middleware

I have controller named 'AdminController'
And I have a lot of functions in there. The problem is that I dont want in every function user IF statement just like this:
public function index(Request $request)
{
if(Auth::check() && $request->user()->is_admin())
{
return view('admin.index');
}
else
{
flash()->error('You dont have permissions!');
return redirect('home');
}
}
How can I make it more simple with middleware so I could make everything work without using IF statement in every function ?
Create a middleware
php artisan make:middleware IsAdmin
Customize app/Http/Middleware/IsAdmin.php
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
class IsAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && $request->user()->is_admin())
{
return $next($request);
}
flash()->error('You dont have permissions!');
return redirect('home');
}
}
Finally register and use the middleware

Resources