-
Notifications
You must be signed in to change notification settings - Fork 0
/
Auth.php
70 lines (58 loc) · 1.77 KB
/
Auth.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
64
65
66
67
68
69
70
<?php
use \Firebase\JWT\JWT;
require_once("JWT\JWT.php");
require_once("UserDbModel.php");
class Auth
{
private static $key = "123";
public static function createToken($userID)
{
$payload = $userID;
return JWT::encode($payload, self::$key);
}
public static function checkAuthenticated()
{
if (!array_key_exists("Authorization", getallheaders())) {
return null;
}
$token = getallheaders()["Authorization"];
$token = explode(" ", $token)[1];
$payload = JWT::decode($token, self::$key, array('HS256'));
if (!$payload) {
return null;
}
$existingUser = UserDbModel::FindUserByID($payload);
if (!$existingUser) {
throw new AuthException();
}
return $payload;
}
// POST -- /auth/register
public function Register()
{
$data = json_decode(file_get_contents('php://input'), true);
$email = $data["email"];
$pass = password_hash($data["password"], PASSWORD_BCRYPT);
$existingUser = UserDbModel::FindUser($email);
if (!$existingUser) {
$userID = UserDbModel::AddUser($email, $pass);
return self::createToken($userID);
} else {
throw new Exception();
}
}
// POST -- /auth/login
public function Login()
{
$data = json_decode(file_get_contents('php://input'), true);
$email = $data["email"];
$pass = $data["password"];
$user = UserDbModel::FindUser($email);
if ($user) {
if ($user["email"] == $email && password_verify($pass, $user["password"])) {
return self::createToken($user["user_id"]);
}
}
throw new AuthException();
}
}