2023-01-11 04:54:25 -05:00
|
|
|
import { defineStore } from 'pinia'
|
2023-11-18 16:30:57 -05:00
|
|
|
import { jwtDecode } from 'jwt-decode'
|
2023-09-26 03:29:46 -04:00
|
|
|
|
2023-01-11 04:54:25 -05:00
|
|
|
export const useAuth = defineStore('auth', {
|
|
|
|
state: () => ({
|
|
|
|
isLogin: false,
|
|
|
|
jwtToken: '',
|
|
|
|
authHeader: {},
|
2023-09-26 03:29:46 -04:00
|
|
|
role: '',
|
2023-01-11 04:54:25 -05:00
|
|
|
}),
|
|
|
|
|
|
|
|
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.jwtToken = ''
|
|
|
|
this.authHeader = {}
|
|
|
|
},
|
|
|
|
|
|
|
|
async obtainToken(username: string, password: string) {
|
|
|
|
let code = 0
|
|
|
|
const payload = {
|
|
|
|
username,
|
|
|
|
password,
|
|
|
|
}
|
|
|
|
|
2024-02-21 11:18:23 -05:00
|
|
|
await $fetch<LoginObj>('/auth/login/', {
|
2023-01-11 04:54:25 -05:00
|
|
|
method: 'POST',
|
|
|
|
body: JSON.stringify(payload),
|
2024-02-21 11:18:23 -05:00
|
|
|
async onResponse({ response }) {
|
2023-01-11 04:54:25 -05:00
|
|
|
code = response.status
|
2024-02-21 11:18:23 -05:00
|
|
|
},
|
|
|
|
})
|
2023-01-11 04:54:25 -05:00
|
|
|
.then((response) => {
|
2024-02-21 11:18:23 -05:00
|
|
|
this.updateToken(response.user?.token)
|
|
|
|
const decodedToken = jwtDecode<JwtPayloadExt>(response.user?.token)
|
2023-09-26 03:29:46 -04:00
|
|
|
this.isLogin = true
|
|
|
|
this.role = decodedToken.role
|
2023-01-11 04:54:25 -05:00
|
|
|
})
|
2024-02-21 11:18:23 -05:00
|
|
|
.catch(() => {})
|
2023-01-11 04:54:25 -05:00
|
|
|
|
|
|
|
return code
|
|
|
|
},
|
|
|
|
|
|
|
|
inspectToken() {
|
|
|
|
let token = useCookie('token').value
|
|
|
|
|
|
|
|
if (token) {
|
|
|
|
this.updateToken(token)
|
2023-09-26 03:29:46 -04:00
|
|
|
const decodedToken = jwtDecode<JwtPayloadExt>(token)
|
2023-01-11 04:54:25 -05:00
|
|
|
const timestamp = Date.now() / 1000
|
|
|
|
const expireToken = decodedToken.exp
|
2023-09-26 03:29:46 -04:00
|
|
|
this.role = decodedToken.role
|
2023-01-11 04:54:25 -05:00
|
|
|
|
|
|
|
if (expireToken && this.jwtToken && expireToken - timestamp > 15) {
|
2023-09-26 03:29:46 -04:00
|
|
|
this.isLogin = true
|
2023-01-11 04:54:25 -05:00
|
|
|
} else {
|
2024-02-21 11:18:23 -05:00
|
|
|
// Prompt user to re-login.
|
2023-09-26 03:29:46 -04:00
|
|
|
this.isLogin = false
|
2023-01-11 04:54:25 -05:00
|
|
|
}
|
|
|
|
} else {
|
2023-09-26 03:29:46 -04:00
|
|
|
this.isLogin = false
|
2023-01-11 04:54:25 -05:00
|
|
|
}
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|