v1.0.0.0
StocketBase
- <?php
-
- declare(strict_types=1);
-
- if (count(get_included_files()) === 1) {
- http_response_code(403);
- exit;
- }
-
- $accountId = (int) $currentUser['id'];
- $twoFactorEnabled = TwoFactor::isEnabled($currentUser);
-
- $confirmIdentity = static function () use ($currentUser, $accountId): ?string {
- $wait = LoginThrottle::secondsUntilAllowed('totp_manage', (string) $accountId);
- if ($wait > 0) {
- return LoginThrottle::message($wait);
- }
-
- $passwordValid = password_verify((string) ($_POST['password'] ?? ''), (string) $currentUser['password_hash']);
- if (!$passwordValid || !TwoFactor::verify($currentUser, (string) ($_POST['code'] ?? ''))) {
- LoginThrottle::recordFailure('totp_manage', (string) $accountId);
- return 'The password or the code is not correct.';
- }
-
- LoginThrottle::clear('totp_manage', (string) $accountId);
-
- return null;
- };
-
- if ($action === 'totp_begin') {
- if (!$twoFactorEnabled) {
- $_SESSION['totp_setup_secret'] = Totp::generateSecret();
- }
-
- return [null, 'success', true];
- }
-
- if ($action === 'totp_cancel') {
- unset($_SESSION['totp_setup_secret']);
-
- return [null, 'success', true];
- }
-
- if ($action === 'totp_confirm') {
- $secret = (string) ($_SESSION['totp_setup_secret'] ?? '');
- if ($twoFactorEnabled || $secret === '') {
- return ['Start the setup again.', 'error', false];
- }
-
- $wait = LoginThrottle::secondsUntilAllowed('totp_setup', (string) $accountId);
- if ($wait > 0) {
- return [LoginThrottle::message($wait), 'error', false];
- }
-
- $step = Totp::verify($secret, (string) ($_POST['code'] ?? ''), null);
- if ($step === null) {
- LoginThrottle::recordFailure('totp_setup', (string) $accountId);
-
- return ['That code is not valid. Check the time on your phone and try again.', 'error', false];
- }
-
- LoginThrottle::clear('totp_setup', (string) $accountId);
- $_SESSION['totp_new_codes'] = TwoFactor::enable($accountId, $secret, $step);
- unset($_SESSION['totp_setup_secret']);
- ActivityLog::record('security.2fa_enabled', 'account', $accountId);
-
- return [null, 'success', true];
- }
-
- if ($action === 'totp_disable' || $action === 'totp_regenerate') {
- if (!$twoFactorEnabled) {
- return ['Two-factor authentication is not enabled.', 'error', false];
- }
-
- $problem = $confirmIdentity();
- if ($problem !== null) {
- return [$problem, 'error', false];
- }
-
- if ($action === 'totp_disable') {
- TwoFactor::disable($accountId);
- ActivityLog::record('security.2fa_disabled', 'account', $accountId);
- } else {
- $_SESSION['totp_new_codes'] = TwoFactor::regenerateRecoveryCodes($accountId);
- ActivityLog::record('security.2fa_recovery_codes', 'account', $accountId);
- }
-
- return [null, 'success', true];
- }
-
- return ['Unknown action.', 'error', false];
-