2017-08-31 02:11:14 +00:00
|
|
|
<?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;
|
2017-08-31 02:11:14 +00:00
|
|
|
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
|
2017-08-31 02:14:20 +00:00
|
|
|
use Illuminate\Contracts\Config\Repository as ConfigRepository;
|
2017-08-31 02:11:14 +00:00
|
|
|
|
|
|
|
class TwoFactorSetupService
|
|
|
|
{
|
2021-01-23 20:33:34 +00:00
|
|
|
public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
2019-06-22 04:55:09 +00:00
|
|
|
|
2017-08-31 02:11:14 +00:00
|
|
|
/**
|
|
|
|
* TwoFactorSetupService constructor.
|
|
|
|
*/
|
|
|
|
public function __construct(
|
2022-10-14 16:59:20 +00:00
|
|
|
private ConfigRepository $config,
|
|
|
|
private Encrypter $encrypter,
|
|
|
|
private UserRepositoryInterface $repository
|
2017-08-31 02:11:14 +00:00
|
|
|
) {
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2017-11-18 18:35:33 +00:00
|
|
|
* Generate a 2FA token and store it in the database before returning the
|
2019-06-22 04:55:09 +00:00
|
|
|
* QR code URL. This URL will need to be attached to a QR generating service in
|
|
|
|
* order to function.
|
2017-08-31 02:11:14 +00:00
|
|
|
*
|
|
|
|
* @throws \Pterodactyl\Exceptions\Model\DataValidationException
|
|
|
|
* @throws \Pterodactyl\Exceptions\Repository\RecordNotFoundException
|
|
|
|
*/
|
2021-08-03 03:39:12 +00:00
|
|
|
public function handle(User $user): array
|
2017-08-31 02:11:14 +00:00
|
|
|
{
|
2019-06-22 04:55:09 +00:00
|
|
|
$secret = '';
|
|
|
|
try {
|
2021-01-23 20:33:34 +00:00
|
|
|
for ($i = 0; $i < $this->config->get('pterodactyl.auth.2fa.bytes', 16); ++$i) {
|
2019-06-22 04:55:09 +00:00
|
|
|
$secret .= substr(self::VALID_BASE32_CHARACTERS, random_int(0, 31), 1);
|
|
|
|
}
|
2023-02-23 19:30:16 +00:00
|
|
|
} catch (\Exception $exception) {
|
|
|
|
throw new \RuntimeException($exception->getMessage(), 0, $exception);
|
2019-06-22 04:55:09 +00:00
|
|
|
}
|
2017-08-31 02:11:14 +00:00
|
|
|
|
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),
|
|
|
|
]);
|
2017-08-31 02:11:14 +00:00
|
|
|
|
2020-07-03 04:14:53 +00:00
|
|
|
$company = urlencode(preg_replace('/\s/', '', $this->config->get('app.name')));
|
2019-06-22 04:55:09 +00:00
|
|
|
|
2021-08-03 03:39:12 +00:00
|
|
|
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,
|
|
|
|
];
|
2017-08-31 02:11:14 +00:00
|
|
|
}
|
|
|
|
}
|