Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Services/Users/TwoFactorSetupService.php
10277 views
1
<?php
2
3
namespace Pterodactyl\Services\Users;
4
5
use Pterodactyl\Models\User;
6
use Illuminate\Contracts\Encryption\Encrypter;
7
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
8
use Illuminate\Contracts\Config\Repository as ConfigRepository;
9
10
class TwoFactorSetupService
11
{
12
public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
13
14
/**
15
* TwoFactorSetupService constructor.
16
*/
17
public function __construct(
18
private ConfigRepository $config,
19
private Encrypter $encrypter,
20
private UserRepositoryInterface $repository,
21
) {
22
}
23
24
/**
25
* Generate a 2FA token and store it in the database before returning the
26
* QR code URL. This URL will need to be attached to a QR generating service in
27
* order to function.
28
*
29
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
30
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
31
*/
32
public function handle(User $user): array
33
{
34
$secret = '';
35
try {
36
for ($i = 0; $i < $this->config->get('pterodactyl.auth.2fa.bytes', 16); ++$i) {
37
$secret .= substr(self::VALID_BASE32_CHARACTERS, random_int(0, 31), 1);
38
}
39
} catch (\Exception $exception) {
40
throw new \RuntimeException($exception->getMessage(), 0, $exception);
41
}
42
43
$this->repository->withoutFreshModel()->update($user->id, [
44
'totp_secret' => $this->encrypter->encrypt($secret),
45
]);
46
47
$company = urlencode(preg_replace('/\s/', '', $this->config->get('app.name')));
48
49
return [
50
'image_url_data' => sprintf(
51
'otpauth://totp/%1$s:%2$s?secret=%3$s&issuer=%1$s',
52
rawurlencode($company),
53
rawurlencode($user->email),
54
rawurlencode($secret),
55
),
56
'secret' => $secret,
57
];
58
}
59
}
60
61