This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathAuth.php
102 lines (87 loc) · 2.34 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace Conduit\Services\Auth;
use Conduit\Models\User;
use DateTime;
use Firebase\JWT\JWT;
use Illuminate\Database\Capsule\Manager;
use Slim\Collection;
use Slim\Http\Request;
class Auth
{
const SUBJECT_IDENTIFIER = 'username';
/**
* @var \Illuminate\Database\Capsule\Manager
*/
private $db;
/**
* @var array
*/
private $appConfig;
/**
* Auth constructor.
*
* @param \Illuminate\Database\Capsule\Manager $db
* @param array|\Slim\Collection $appConfig
*/
public function __construct(Manager $db, Collection $appConfig)
{
$this->db = $db;
$this->appConfig = $appConfig;
}
/**
* Generate a new JWT token
*
* @param \Conduit\Models\User $user
*
* @return string
* @internal param string $subjectIdentifier The username of the subject user.
*
*/
public function generateToken(User $user)
{
$now = new DateTime();
$future = new DateTime("now +2 hours");
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"jti" => base64_encode(random_bytes(16)),
'iss' => $this->appConfig['app']['url'], // Issuer
"sub" => $user->{self::SUBJECT_IDENTIFIER},
];
$secret = $this->appConfig['jwt']['secret'];
$token = JWT::encode($payload, $secret, "HS256");
return $token;
}
/**
* Attempt to find the user based on email and verify password
*
* @param $email
* @param $password
*
* @return bool|\Conduit\Models\User
*/
public function attempt($email, $password)
{
if ( ! $user = User::where('email', $email)->first()) {
return false;
}
if (password_verify($password, $user->password)) {
return $user;
}
return false;
}
/**
* Retrieve a user by the JWT token from the request
*
* @param \Slim\Http\Request $request
*
* @return User|null
*/
public function requestUser(Request $request)
{
// Should add more validation to the present and validity of the token?
if ($token = $request->getAttribute('token')) {
return User::where(static::SUBJECT_IDENTIFIER, '=', $token->sub)->first();
};
}
}