Authenticate.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Support\Facades\Auth;
  5. class Authenticate
  6. {
  7. /**
  8. * Handle an incoming request.
  9. *
  10. * @param \Illuminate\Http\Request $request
  11. * @param \Closure $next
  12. * @param string ...$guards
  13. * @return mixed
  14. */
  15. public function handle($request, Closure $next, ...$guards)
  16. {
  17. if ($this->check($guards)) {
  18. return $next($request);
  19. }
  20. if ($request->ajax() || $request->wantsJson()) {
  21. return response('Unauthorized.', 401);
  22. } else {
  23. return redirect()->guest('login');
  24. }
  25. }
  26. /**
  27. * Determine if the user is logged in to any of the given guards.
  28. *
  29. * @param array $guards
  30. * @return bool
  31. */
  32. protected function check(array $guards)
  33. {
  34. if (empty($guards)) {
  35. return Auth::check();
  36. }
  37. foreach ($guards as $guard) {
  38. if (Auth::guard($guard)->check()) {
  39. Auth::shouldUse($guard);
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. }