v1.0.0.1
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 code isn\'t right.';
- }
-
- 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 ['That took too long. Please 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 didn\'t work. Make sure the time on your phone is correct 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-step login is already off.', '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 ['Something went wrong. Please try again.', 'error', false];
-