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

60 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Pterodactyl\Services\Users;
2017-08-31 02:14:20 +00:00
use Pterodactyl\Models\User;
2017-11-18 18:35:33 +00:00
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
2017-08-31 02:14:20 +00:00
use Illuminate\Contracts\Config\Repository as ConfigRepository;
class TwoFactorSetupService
{
2021-01-23 20:33:34 +00:00
public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
/**
* TwoFactorSetupService constructor.
*/
public function __construct(
private ConfigRepository $config,
private Encrypter $encrypter,
private UserRepositoryInterface $repository
) {
}
/**
2017-11-18 18:35:33 +00: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.
*
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
*/
public function handle(User $user): array
{
$secret = '';
try {
2021-01-23 20:33:34 +00: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);
}
2022-11-29 17:53:59 +00:00
} catch (\Exception $exception) {
throw new \RuntimeException($exception->getMessage(), 0, $exception);
}
2018-01-05 22:33:50 +00:00
$this->repository->withoutFreshModel()->update($user->id, [
2017-11-18 18:35:33 +00:00
'totp_secret' => $this->encrypter->encrypt($secret),
]);
2020-07-03 04:14:53 +00: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,
];
}
}