-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtokenGuard.js
100 lines (71 loc) · 2.34 KB
/
tokenGuard.js
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
const GuardHelpers = require('./guardHelpers')
const { implement } = require('@ostro/support/function')
const { createHash } = require('crypto');
const Crypt = require('@ostro/support/facades/crypt')
class TokenGuard extends GuardHelpers {
$hash;
$request;
$provider;
$inputKey = 'api_token';
$storageKey = 'api_token';
constructor($provider, $request, $inputKey = 'api_token', $storageKey = 'api_token', $hash = false) {
super()
this.$hash = $hash;
this.$request = $request;
this.$provider = $provider;
this.$inputKey = $inputKey;
this.$storageKey = $storageKey;
}
async hasValidCredentials($user, $credentials) {
return !is_null($user) && await this.$provider.validateCredentials($user, $credentials);
}
async attempt($credentials = {}) {
let $user = await this.$provider.retrieveByCredentials($credentials);
this.$lastAttempted = $user;
if (await this.hasValidCredentials($user, $credentials)) {
this.$user = $user;
await this.user();
return true;
}
return false;
}
async user() {
if (!is_null(this.$user)) {
return this.$user;
}
let $user = null;
let $token = this.getTokenForRequest();
if (!empty($token)) {
$user = await this.$provider.retrieveByCredentials({
[this.$storageKey]: this.$hash ? createHash('sha256').update($token).digest('hex') : $token,
});
}
return this.$user = $user;
}
getTokenForRequest() {
let $token = this.$request.getQuery(this.$inputKey);
if (empty($token)) {
$token = this.$request.input(this.$inputKey);
}
if (empty($token)) {
$token = this.$request.bearerToken();
}
if (empty($token)) {
$token = this.$request.getPassword();
}
return $token;
}
async validate($credentials = {}) {
if (empty($credentials[this.$inputKey])) {
return false;
}
$credentials = {
[this.$storageKey]: $credentials[this.$inputKey]
};
if (await this.$provider.retrieveByCredentials($credentials)) {
return true;
}
return false;
}
}
module.exports = TokenGuard