2FAuth/app/Http/Middleware/Authenticate.php

65 lines
2.3 KiB
PHP
Raw Normal View History

2019-05-20 07:37:41 +02:00
<?php
namespace App\Http\Middleware;
2024-07-03 11:14:49 +02:00
use App\Events\VisitedByProxyUser;
2019-05-20 07:37:41 +02:00
use Illuminate\Auth\Middleware\Authenticate as Middleware;
2024-07-03 11:14:49 +02:00
use Illuminate\Support\Carbon;
2023-02-25 21:12:10 +01:00
use Illuminate\Support\Facades\App;
2024-07-03 11:14:49 +02:00
use Illuminate\Support\Facades\Auth;
2019-05-20 07:37:41 +02:00
class Authenticate extends Middleware
{
/**
* Determine if the user is logged in to any of the given guards.
*
* @param \Illuminate\Http\Request $request
* @return void
*
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function authenticate($request, array $guards)
{
2024-07-03 11:14:49 +02:00
$proxyGuard = 'reverse-proxy-guard';
if (empty($guards)) {
// Will retreive the default guard
$guards = [null];
2022-11-22 15:15:52 +01:00
} else {
// If reverse proxy is defined as the default guard, we force the
// authentication against this only guard.
if (config('auth.defaults.guard') === $proxyGuard) {
$guards = [$proxyGuard];
}
}
foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
$this->auth->shouldUse($guard);
2022-11-22 15:15:52 +01:00
// We now have an authenticated user so we override the locale already set
// by the SetLanguage global middleware
2024-07-03 11:14:49 +02:00
$user = $this->auth->guard()->user();
$lang = $user->preferences['lang'];
if (in_array($lang, config('2fauth.locales')) && ! App::isLocale($lang)) {
App::setLocale($lang);
}
2024-07-03 11:14:49 +02:00
// Unlike the SessionGuard, the reverse-proxy-guard does not implement an attempt()
// method when it comes to log the user in. So auth events (Login, FailedLogin, etc..) are not
// fired by the guard, they are not even relevant.
// So when using the reverse-proxy-guard, we fire a VisitedByProxyUser event from here, but only
// if the user last request is older than 15 minutes to avoid too many dispatchs
if ($guard === $proxyGuard && (! $user->last_seen_at || Carbon::parse($user->last_seen_at) < Carbon::now()->subMinutes(15))) {
event(new VisitedByProxyUser($user));
}
return;
}
}
$this->unauthenticated($request, $guards);
}
2022-11-22 15:15:52 +01:00
}