-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_middleware.php
More file actions
56 lines (45 loc) · 1.86 KB
/
Copy pathauth_middleware.php
File metadata and controls
56 lines (45 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
// 1. Include the autoloader so we can handle token decoding
require_once __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
function authenticate_user($pdo) {
// 2. Extract the HTTP Authorization Header
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? null;
if (!$authHeader) {
http_response_code(401);
echo json_encode(["error" => "Authorization header missing"]);
exit;
}
// 3. Extract the clean token from the 'Bearer <token>' format
if (!preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
http_response_code(401);
echo json_encode(["error" => "Invalid authorization header format. Use 'Bearer <token>'"]);
exit;
}
$jwt = $matches[1];
$jwtSecret = $_ENV['JWT_SECRET'] ?? null;
try {
// 4. Decode and cryptographically verify the token signatures
$decoded = JWT::decode($jwt, new Key($jwtSecret, 'HS256'));
// 5. Convert the decoded object properties into a clean associative array
$claims = (array) $decoded;
// 6. Cross-verify against the database to guarantee the user still exists
$stmt = $pdo->prepare("SELECT id, username FROM users WHERE username = :username");
$stmt->execute([':username' => $claims['sub']]);
$user = $stmt->fetch();
if (!$user) {
http_response_code(401);
echo json_encode(["error" => "User record no longer exists"]);
exit;
}
// 7. Return the verified user array data to the calling route handler
return $user;
} catch (\Exception $e) {
// Catch expired or tampered signatures safely
http_response_code(401);
echo json_encode(["error" => "Token verification failed: " . $e->getMessage()]);
exit;
}
}