simplify obtainToken

This commit is contained in:
jb-alvarado 2024-02-21 17:18:23 +01:00
parent 8eb543ddae
commit 3e25207863
2 changed files with 24 additions and 23 deletions

View File

@ -1,10 +1,5 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { jwtDecode } from 'jwt-decode' import { jwtDecode } from 'jwt-decode'
import { type JwtPayload } from 'jwt-decode'
interface JwtPayloadExt extends JwtPayload {
role: string
}
export const useAuth = defineStore('auth', { export const useAuth = defineStore('auth', {
state: () => ({ state: () => ({
@ -42,27 +37,21 @@ export const useAuth = defineStore('auth', {
password, password,
} }
await fetch('/auth/login/', { await $fetch<LoginObj>('/auth/login/', {
method: 'POST', method: 'POST',
headers: new Headers([['content-type', 'application/json;charset=UTF-8']]), headers: new Headers([['content-type', 'application/json;charset=UTF-8']]),
body: JSON.stringify(payload), body: JSON.stringify(payload),
}) async onResponse({ response }) {
.then((response) => {
code = response.status code = response.status
return response },
}) })
.then((response) => response.json())
.then((response) => { .then((response) => {
this.updateToken(response.user.token) this.updateToken(response.user?.token)
const decodedToken = jwtDecode<JwtPayloadExt>(response.user.token) const decodedToken = jwtDecode<JwtPayloadExt>(response.user?.token)
this.isLogin = true this.isLogin = true
this.role = decodedToken.role this.role = decodedToken.role
}) })
.catch((error) => { .catch(() => {})
if (error.status) {
code = error.status
}
})
return code return code
}, },
@ -70,10 +59,6 @@ export const useAuth = defineStore('auth', {
inspectToken() { inspectToken() {
let token = useCookie('token').value let token = useCookie('token').value
if (token === null) {
token = ''
}
if (token) { if (token) {
this.updateToken(token) this.updateToken(token)
const decodedToken = jwtDecode<JwtPayloadExt>(token) const decodedToken = jwtDecode<JwtPayloadExt>(token)
@ -84,7 +69,7 @@ export const useAuth = defineStore('auth', {
if (expireToken && this.jwtToken && expireToken - timestamp > 15) { if (expireToken && this.jwtToken && expireToken - timestamp > 15) {
this.isLogin = true this.isLogin = true
} else { } else {
// Prompt user to re login. // Prompt user to re-login.
this.isLogin = false this.isLogin = false
} }
} else { } else {

16
types/index.d.ts vendored
View File

@ -1,6 +1,22 @@
import { type JwtPayload } from 'jwt-decode'
export {} export {}
declare global { declare global {
interface JwtPayloadExt extends JwtPayload {
role: string
}
interface LoginObj {
message: string
user?: {
id: number
mail: string
username: string
token
}
}
interface GuiConfig { interface GuiConfig {
id: number id: number
config_path: string config_path: string