-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.js
56 lines (44 loc) · 1.23 KB
/
auth.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
var currentUser = undefined
async function getCurrentUser() {
//Fetch current user data
async function getUser() {
try {
const response = await fetch(`http://localhost:3030/users/me`, {
headers: {
'Content-Type': 'application/json',
'x-access-token': localStorage.getItem('x-access-token')
},
})
if(response.status === 200){
return response.json() // parses JSON response into native JavaScript objects
}
return null
} catch (error) {
return null
}
}
if(currentUser === undefined){
if(localStorage.getItem('x-access-token') && localStorage.getItem('user-data')){
const curUsr = await getUser()
if(!curUsr){
localStorage.removeItem('user-data')
localStorage.removeItem('x-access-token')
currentUser = null
return currentUser
}else{
currentUser = curUsr
return currentUser
}
}else{
currentUser = null
return currentUser
}
}
return currentUser
}
function logTheUserOut() {
localStorage.removeItem('user-data')
localStorage.removeItem('x-access-token')
currentUser = null
location.reload()
}