初始化仓库及v1.0.0提交
This commit is contained in:
37
app/Middleware/AuthMiddleware.php
Normal file
37
app/Middleware/AuthMiddleware.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Middleware;
|
||||
|
||||
use App\Config\AppConfig;
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
class AuthMiddleware
|
||||
{
|
||||
public static function handle(): void
|
||||
{
|
||||
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
|
||||
|
||||
if (!$authHeader || !preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'message' => '请先登录']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$token = $matches[1];
|
||||
|
||||
try {
|
||||
$jwtSecret = AppConfig::get('jwtSecret');
|
||||
$decoded = JWT::decode($token, new Key($jwtSecret, 'HS256'));
|
||||
$GLOBALS['auth_user'] = [
|
||||
'userId' => $decoded->userId,
|
||||
'username' => $decoded->username,
|
||||
'role' => $decoded->role
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'message' => '请先登录']);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user