-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathauth.js
More file actions
106 lines (87 loc) · 2.33 KB
/
Copy pathauth.js
File metadata and controls
106 lines (87 loc) · 2.33 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
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
103
104
105
106
import auth0 from 'auth0-js';
import Constants from 'config/constants';
const storageKey = 'auth-data';
export default class Auth {
accessToken;
idToken;
expiresAt;
auth0 = new auth0.WebAuth({
domain: Constants.auth.DOMAIN,
clientID: Constants.auth.CLIENT_ID,
redirectUri: Constants.auth.CALLBACK_URL,
responseType: 'token id_token',
scope: 'openid',
});
login = () => {
this.auth0.authorize();
};
handleAuthentication() {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (err) {
reject(err);
} else {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
}
resolve();
}
});
});
}
getAccessToken() {
return this.accessToken;
}
getIdToken() {
return this.idToken;
}
setSession(authResult) {
const expiresAt = authResult.expiresIn * 1000 + new Date().getTime();
// Set isLoggedIn flag in localStorage
localStorage.setItem(
storageKey,
JSON.stringify({
accessToken: authResult.accessToken,
idToken: authResult.idToken,
expiresAt,
}),
);
// Set the time that the access token will expire at
this.accessToken = authResult.accessToken;
this.idToken = authResult.idToken;
this.expiresAt = expiresAt;
}
loadSession() {
const json = localStorage.getItem(storageKey);
if (json) {
const session = JSON.parse(json);
this.accessToken = session.accessToken;
this.idToken = session.idToken;
this.expiresAt = session.expiresAt;
}
}
renewSession() {
this.auth0.checkSession({}, (err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
} else if (err) {
this.logout();
console.log(err);
}
});
}
logout = () => {
// Remove tokens and expiry time from memory
this.accessToken = null;
this.idToken = null;
this.expiresAt = 0;
// Remove token from localStorage
localStorage.removeItem(storageKey);
};
isAuthenticated() {
// Check whether the current time is past the
// access token's expiry time
let expiresAt = this.expiresAt;
return new Date().getTime() < expiresAt;
}
}