2017-08-30 21:11:14 -05:00
|
|
|
<?php
|
|
|
|
|
|
2024-03-12 22:39:16 -04:00
|
|
|
namespace App\Services\Users;
|
2017-08-30 21:11:14 -05:00
|
|
|
|
2024-03-12 22:39:16 -04:00
|
|
|
use App\Models\User;
|
2017-08-30 21:11:14 -05:00
|
|
|
|
|
|
|
|
class TwoFactorSetupService
|
|
|
|
|
{
|
2021-01-23 12:33:34 -08:00
|
|
|
public const VALID_BASE32_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
2019-06-21 21:55:09 -07:00
|
|
|
|
2017-08-30 21:11:14 -05:00
|
|
|
/**
|
2017-11-18 13:35:33 -05:00
|
|
|
* Generate a 2FA token and store it in the database before returning the
|
2019-06-21 21:55:09 -07:00
|
|
|
* QR code URL. This URL will need to be attached to a QR generating service in
|
|
|
|
|
* order to function.
|
2017-08-30 21:11:14 -05:00
|
|
|
*
|
2025-03-03 14:41:19 -05:00
|
|
|
* @return array{image_url_data: string, secret: string}
|
|
|
|
|
*
|
2024-03-12 22:39:16 -04:00
|
|
|
* @throws \App\Exceptions\Model\DataValidationException
|
2017-08-30 21:11:14 -05:00
|
|
|
*/
|
2021-08-03 05:39:12 +02:00
|
|
|
public function handle(User $user): array
|
2017-08-30 21:11:14 -05:00
|
|
|
{
|
2019-06-21 21:55:09 -07:00
|
|
|
$secret = '';
|
|
|
|
|
try {
|
2024-03-19 04:59:19 -04:00
|
|
|
for ($i = 0; $i < config('panel.auth.2fa.bytes', 16); $i++) {
|
2019-06-21 21:55:09 -07:00
|
|
|
$secret .= substr(self::VALID_BASE32_CHARACTERS, random_int(0, 31), 1);
|
|
|
|
|
}
|
2023-02-23 12:30:16 -07:00
|
|
|
} catch (\Exception $exception) {
|
|
|
|
|
throw new \RuntimeException($exception->getMessage(), 0, $exception);
|
2019-06-21 21:55:09 -07:00
|
|
|
}
|
2017-08-30 21:11:14 -05:00
|
|
|
|
2024-05-28 15:24:20 +02:00
|
|
|
$user->totp_secret = $secret;
|
2024-03-16 19:10:31 -04:00
|
|
|
$user->save();
|
2017-08-30 21:11:14 -05:00
|
|
|
|
2024-03-19 04:59:19 -04:00
|
|
|
$company = urlencode(preg_replace('/\s/', '', config('app.name')));
|
2019-06-21 21:55:09 -07:00
|
|
|
|
2021-08-03 05:39:12 +02: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-30 21:11:14 -05:00
|
|
|
}
|
|
|
|
|
}
|