-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthMiddleware.php
More file actions
66 lines (58 loc) · 1.77 KB
/
AuthMiddleware.php
File metadata and controls
66 lines (58 loc) · 1.77 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
57
58
59
60
61
62
63
64
65
66
<?php
require __DIR__ . '/classes/JwtHandler.php';
class Auth extends JwtHandler
{
protected $db;
protected $headers;
protected $token;
public function __construct($db, $headers)
{
parent::__construct();
$this->db = $db;
$this->headers = $headers;
}
public function isValid()
{
if (array_key_exists('Authorization', $this->headers) && preg_match('/Bearer\s(\S+)/', $this->headers['Authorization'], $matches)) {
$data = $this->jwtDecodeData($matches[1]);
if (
isset($data['data']->user_id) &&
$user = $this->fetchUser($data['data']->user_id)
) :
http_response_code(200);
return [
"success" => 1,
"user" => $user
];
else :
http_response_code(401);
return [
"success" => 0,
"message" => $data['message'],
];
endif;
} else {
http_response_code(400);
return [
"success" => 0,
"message" => "Token not found in request"
];
}
}
protected function fetchUser($user_id)
{
try {
$fetch_user_by_id = "SELECT `name`,`email` FROM `users` WHERE `id`=:id";
$query_stmt = $this->db->prepare($fetch_user_by_id);
$query_stmt->bindValue(':id', $user_id, PDO::PARAM_INT);
$query_stmt->execute();
if ($query_stmt->rowCount()) :
return $query_stmt->fetch(PDO::FETCH_ASSOC);
else :
return false;
endif;
} catch (PDOException $e) {
return null;
}
}
}