3

I need to authenticate users in two different ways using one model. Is it possible to define two guards and chose the preferable one e.g. on the controller level?

Also maybe there is a better way to implement that using laravel? Would appreciate any thoughts.

mom__66
  • 53
  • 10
  • `authenticate users in two different ways` what it means? Can elaborate it? any example. – Prashant Deshmukh..... Dec 06 '19 at 12:32
  • @PrashantDeshmukh..... I mean there should be different login flows with different logic. E.g. some users are not present in my DB on their first login and I need to add additional processing. Also there are two different API endpoints with different request parameters required for login, so I can define which flow to use according to endpoint used. It's possible to simply add if/else to my main guard and it will work, but I'm trying to find some better way. – mom__66 Dec 06 '19 at 12:39

1 Answers1

2

yes it is possible. You should create two different LoginControllers with assigned routes, create two different Auth middleware and probably also change RedirectIfAuthenticated middleware a little bit.

In both LoginControllers you should define you guard like so:

protected function guard()
{
    return Auth::guard('admin');
}

And if you want to separete routes for your guards than also in RedirectIfAuthenticated Middleware you shold define redirections for both guards

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {

        if($guard == 'admin') return redirect('/admin');
        return redirect('/');
    }

    return $next($request);
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Milena Grygier
  • 376
  • 1
  • 7