43 lines
1.2 KiB
PHP
43 lines
1.2 KiB
PHP
<?php
|
|
namespace App\Middleware;
|
|
|
|
use App\Helpers\Response;
|
|
use App\Models\User;
|
|
|
|
/**
|
|
* Class TwoFactorGuard
|
|
* 2FA (Google Authenticator TOTP) Verification Guard Middleware
|
|
*
|
|
* @package App\Middleware
|
|
*/
|
|
class TwoFactorGuard
|
|
{
|
|
/**
|
|
* Ensure user has verified 2FA if enabled on their account
|
|
*/
|
|
public static function check(): void
|
|
{
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
$userId = $_SESSION['user_id'] ?? null;
|
|
if (!$userId) {
|
|
Response::error("Unauthorized: Please login first", 401);
|
|
}
|
|
|
|
$userModel = new User();
|
|
$user = $userModel->find((int)$userId);
|
|
|
|
if ($user && (int)$user['two_factor_enabled'] === 1) {
|
|
$isVerified = $_SESSION['2fa_verified'] ?? false;
|
|
if (!$isVerified) {
|
|
Response::error("2FA Required: บัญชีของท่านเปิดใช้งาน 2-Factor Authentication กรุณายืนยันรหัส TOTP 6 หลักจาก Google Authenticator ก่อนใช้งาน", 403, [
|
|
'require_2fa' => true,
|
|
'redirect' => '/verify-2fa',
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|