misc_pterodactyl-panel/app/Services/Users/TwoFactorSetupService.php

56 lines
1.6 KiB
PHP
Raw Normal View History

<?php
namespace Pterodactyl\Services\Users;
use Exception;
use RuntimeException;
2017-08-30 21:14:20 -05:00
use Pterodactyl\Models\User;
2017-11-18 13:35:33 -05:00
use Illuminate\Contracts\Encryption\Encrypter;
2017-08-30 21:14:20 -05:00
use Illuminate\Contracts\Config\Repository as ConfigRepository;
class TwoFactorSetupService
{
2021-01-23 12:33:34 -08:00
public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/**
* TwoFactorSetupService constructor.
*/
public function __construct(
private ConfigRepository $config,
2022-10-22 03:59:36 -04:00
private Encrypter $encrypter
) {
}
/**
2017-11-18 13:35:33 -05:00
* Generate a 2FA token and store it in the database before returning the
* QR code URL. This URL will need to be attached to a QR generating service in
* order to function.
*/
public function handle(User $user): array
{
$secret = '';
try {
2021-01-23 12:33:34 -08:00
for ($i = 0; $i < $this->config->get('pterodactyl.auth.2fa.bytes', 16); ++$i) {
$secret .= substr(self::VALID_BASE32_CHARACTERS, random_int(0, 31), 1);
}
} catch (Exception $exception) {
throw new RuntimeException($exception->getMessage(), 0, $exception);
}
2022-10-22 03:59:36 -04:00
$user->totp_secret = $this->encrypter->encrypt($secret);
$user->save();
2020-07-02 21:14:53 -07:00
$company = urlencode(preg_replace('/\s/', '', $this->config->get('app.name')));
return [
'image_url_data' => sprintf(
'otpauth://totp/%1$s:%2$s?secret=%3$s&issuer=%1$s',
rawurlencode($company),
rawurlencode($user->email),
rawurlencode($secret),
),
'secret' => $secret,
];
}
}