Add back 2fa requirement middleware (#1897)

Co-authored-by: MartinOscar <40749467+rmartinoscar@users.noreply.github.com>
This commit is contained in:
Boy132 2025-11-24 00:01:29 +01:00 committed by GitHub
parent 65bb99e2b0
commit 07763d912b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 84 additions and 24 deletions

View File

@ -0,0 +1,18 @@
<?php
namespace App\Exceptions\Http;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class TwoFactorAuthRequiredException extends HttpException implements HttpExceptionInterface
{
/**
* TwoFactorAuthRequiredException constructor.
*/
public function __construct(?\Throwable $previous = null)
{
parent::__construct(Response::HTTP_BAD_REQUEST, 'Two-factor authentication is required on this account in order to access this endpoint.', $previous);
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace App\Http\Middleware;
use App\Exceptions\Http\TwoFactorAuthRequiredException;
use App\Filament\Pages\Auth\EditProfile;
use App\Livewire\AlertBanner;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class RequireTwoFactorAuthentication
{
public const LEVEL_NONE = 0;
public const LEVEL_ADMIN = 1;
public const LEVEL_ALL = 2;
/**
* Check the user state on the incoming request to determine if they should be allowed to
* proceed or not. This checks if the Panel is configured to require 2FA on an account in
* order to perform actions. If so, we check the level at which it is required (all users
* or just admins) and then check if the user has enabled it for their account.
*
* @throws \App\Exceptions\Http\TwoFactorAuthRequiredException
*/
public function handle(Request $request, \Closure $next): mixed
{
/** @var ?User $user */
$user = $request->user();
// Auth and profile endpoints should always be available
if (!$user || $request->routeIs('*auth.*')) {
return $next($request);
}
$level = (int) config('panel.auth.2fa_required');
$has2fa = $user->hasEmailAuthentication() || filled($user->getAppAuthenticationSecret());
if ($level === self::LEVEL_NONE || $has2fa) {
// If this setting is not configured, or the user is already using 2FA then we can just send them right through, nothing else needs to be checked.
return $next($request);
}
if ($level === self::LEVEL_ADMIN && !$user->isAdmin()) {
// If the level is set as admin and the user is not an admin, pass them through as well.
return $next($request);
}
// For API calls return an exception which gets rendered nicely in the API response...
if ($request->isJson() || Str::startsWith($request->path(), '/api')) {
throw new TwoFactorAuthRequiredException();
}
// ... otherwise display banner and redirect to profile
AlertBanner::make('2fa_must_be_enabled')
->body(trans('auth.2fa_must_be_enabled'))
->warning()
->send();
return redirect(EditProfile::getUrl(['tab' => '2fa::data::tab'], panel: 'app'));
}
}

View File

@ -6,7 +6,7 @@ use App\Enums\CustomizationKey;
use App\Filament\Pages\Auth\EditProfile;
use App\Filament\Pages\Auth\Login;
use App\Http\Middleware\LanguageMiddleware;
use App\Models\User;
use App\Http\Middleware\RequireTwoFactorAuthentication;
use Filament\Actions\Action;
use Filament\Auth\MultiFactor\App\AppAuthentication;
use Filament\Auth\MultiFactor\Email\EmailAuthentication;
@ -56,29 +56,6 @@ abstract class PanelProvider extends BasePanelProvider
AppAuthentication::make()->recoverable(),
EmailAuthentication::make(),
])
->requiresMultiFactorAuthentication(function () {
$user = user(); // TODO: get user, see https://github.com/filamentphp/filament/discussions/17695
if ($user) {
$level = (int) config('panel.auth.2fa_required');
// Not required
if ($level === 0) {
return false;
}
// Only admins
if ($level === 1) {
return $user->isAdmin();
}
// All users
if ($level === 2) {
return true;
}
}
return false;
})
->middleware([
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
@ -93,6 +70,7 @@ abstract class PanelProvider extends BasePanelProvider
])
->authMiddleware([
Authenticate::class,
RequireTwoFactorAuthentication::class,
]);
}
}