65 lines
2.1 KiB
PHP
65 lines
2.1 KiB
PHP
<?php
|
|
namespace App\Middleware;
|
|
|
|
use App\Helpers\Response;
|
|
use App\Helpers\Security;
|
|
use App\Models\User;
|
|
|
|
/**
|
|
* Class JwtAuthMiddleware
|
|
* Enterprise JWT Authentication & Session Validation Middleware
|
|
*
|
|
* @package App\Middleware
|
|
*/
|
|
class JwtAuthMiddleware
|
|
{
|
|
/**
|
|
* Handle incoming request validation
|
|
*
|
|
* @return array Authenticated User Data
|
|
*/
|
|
public static function handle(): array
|
|
{
|
|
$headers = getallheaders();
|
|
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
|
|
|
$token = null;
|
|
if (preg_match('/^Bearer\s+(.*?)$/i', $authHeader, $matches)) {
|
|
$token = trim($matches[1]);
|
|
} elseif (!empty($_SESSION['access_token'])) {
|
|
$token = $_SESSION['access_token'];
|
|
}
|
|
|
|
if (empty($token)) {
|
|
Response::error('Unauthorized: No authentication token provided (กรุณาเข้าสู่ระบบ)', 401);
|
|
}
|
|
|
|
$config = require __DIR__ . '/../../config/security.php';
|
|
$secret = $config['jwt']['secret'];
|
|
|
|
$payload = Security::decodeJwt($token, $secret);
|
|
if (!$payload || !isset($payload['sub'])) {
|
|
Response::error('Unauthorized: Invalid or expired token (Token หมดอายุหรือไม่ถูกต้อง)', 401);
|
|
}
|
|
|
|
// Validate user existence and status in DB
|
|
$userModel = new User();
|
|
$user = $userModel->find((int)$payload['sub']);
|
|
|
|
if (!$user || (int)$user['is_active'] !== 1) {
|
|
Response::error('Unauthorized: User account is inactive or deleted', 401);
|
|
}
|
|
|
|
// Set global session context
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
$_SESSION['user_id'] = (int)$user['id'];
|
|
$_SESSION['user_role'] = $user['role'];
|
|
$_SESSION['branch_id'] = (int)($user['branch_id'] ?? 1);
|
|
|
|
unset($user['password_hash'], $user['two_factor_secret'], $user['two_factor_recovery_codes']);
|
|
return $user;
|
|
}
|
|
}
|