-
Notifications
You must be signed in to change notification settings - Fork 9
/
AuthMiddleware.php
63 lines (55 loc) · 1.66 KB
/
AuthMiddleware.php
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
<?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)
) :
return [
"success" => 1,
"user" => $user
];
else :
return [
"success" => 0,
"message" => $data['message'],
];
endif;
} else {
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;
}
}
}