/
auth.ts
94 lines (83 loc) · 2.7 KB
/
auth.ts
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
import { defineStore } from 'pinia'
import { jwtDecode } from 'jwt-decode'
export const useAuth = defineStore('auth', {
state: () => ({
isLogin: false,
jwtToken: '',
authHeader: {},
role: '',
uuid: null as null | string,
}),
getters: {},
actions: {
updateToken(token: string) {
const cookie = useCookie('token', {
path: '/',
maxAge: 60 * 60 * 24 * 365,
sameSite: 'lax',
})
cookie.value = token
this.jwtToken = token
this.authHeader = { Authorization: `Bearer ${token}` }
},
removeToken() {
const cookie = useCookie('token')
cookie.value = null
this.isLogin = false
this.jwtToken = ''
this.authHeader = {}
},
async obtainToken(username: string, password: string) {
let code = 0
const payload = {
username,
password,
}
await $fetch<LoginObj>('/auth/login/', {
method: 'POST',
body: JSON.stringify(payload),
async onResponse({ response }) {
code = response.status
},
})
.then((response) => {
this.updateToken(response.user?.token)
const decodedToken = jwtDecode<JwtPayloadExt>(response.user?.token)
this.isLogin = true
this.role = decodedToken.role
})
.catch(() => {})
return code
},
async obtainUuid() {
await $fetch<DataAuth>('/api/generate-uuid', {
method: 'POST',
headers: this.authHeader,
})
.then((response) => {
this.uuid = response.uuid
})
.catch(() => {
this.uuid = null
})
},
inspectToken() {
const token = useCookie('token').value
if (token) {
this.updateToken(token)
const decodedToken = jwtDecode<JwtPayloadExt>(token)
const timestamp = Date.now() / 1000
const expireToken = decodedToken.exp
this.role = decodedToken.role
if (expireToken && this.jwtToken && expireToken - timestamp > 15) {
this.isLogin = true
} else {
// Prompt user to re-login.
this.isLogin = false
}
} else {
this.isLogin = false
}
},
},
})