Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Http/Middleware/RequireTwoFactorAuthentication.php
10279 views
1
<?php
2
3
namespace Pterodactyl\Http\Middleware;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Http\Request;
7
use Prologue\Alerts\AlertsMessageBag;
8
use Pterodactyl\Exceptions\Http\TwoFactorAuthRequiredException;
9
10
class RequireTwoFactorAuthentication
11
{
12
public const LEVEL_NONE = 0;
13
public const LEVEL_ADMIN = 1;
14
public const LEVEL_ALL = 2;
15
16
/**
17
* The route to redirect a user to enable 2FA.
18
*/
19
protected string $redirectRoute = '/account';
20
21
/**
22
* RequireTwoFactorAuthentication constructor.
23
*/
24
public function __construct(private AlertsMessageBag $alert)
25
{
26
}
27
28
/**
29
* Check the user state on the incoming request to determine if they should be allowed to
30
* proceed or not. This checks if the Panel is configured to require 2FA on an account in
31
* order to perform actions. If so, we check the level at which it is required (all users
32
* or just admins) and then check if the user has enabled it for their account.
33
*
34
* @throws TwoFactorAuthRequiredException
35
*/
36
public function handle(Request $request, \Closure $next): mixed
37
{
38
$user = $request->user();
39
$uri = rtrim($request->getRequestUri(), '/') . '/';
40
$current = $request->route()->getName();
41
42
if (!$user || Str::startsWith($uri, ['/auth/']) || Str::startsWith($current, ['auth.', 'account.'])) {
43
return $next($request);
44
}
45
46
$level = (int) config('pterodactyl.auth.2fa_required');
47
// If this setting is not configured, or the user is already using 2FA then we can just
48
// send them right through, nothing else needs to be checked.
49
//
50
// If the level is set as admin and the user is not an admin, pass them through as well.
51
if ($level === self::LEVEL_NONE || $user->use_totp) {
52
return $next($request);
53
} elseif ($level === self::LEVEL_ADMIN && !$user->root_admin) {
54
return $next($request);
55
}
56
57
// For API calls return an exception which gets rendered nicely in the API response.
58
if ($request->isJson() || Str::startsWith($uri, '/api/')) {
59
throw new TwoFactorAuthRequiredException();
60
}
61
62
$this->alert->danger(trans('auth.2fa_must_be_enabled'))->flash();
63
64
return redirect()->to($this->redirectRoute);
65
}
66
}
67
68