diff --git a/stores/auth.ts b/stores/auth.ts index 6c84f9f3..96331ab4 100644 --- a/stores/auth.ts +++ b/stores/auth.ts @@ -1,10 +1,5 @@ import { defineStore } from 'pinia' import { jwtDecode } from 'jwt-decode' -import { type JwtPayload } from 'jwt-decode' - -interface JwtPayloadExt extends JwtPayload { - role: string -} export const useAuth = defineStore('auth', { state: () => ({ @@ -42,27 +37,21 @@ export const useAuth = defineStore('auth', { password, } - await fetch('/auth/login/', { + await $fetch('/auth/login/', { method: 'POST', headers: new Headers([['content-type', 'application/json;charset=UTF-8']]), body: JSON.stringify(payload), + async onResponse({ response }) { + code = response.status + }, }) .then((response) => { - code = response.status - return response - }) - .then((response) => response.json()) - .then((response) => { - this.updateToken(response.user.token) - const decodedToken = jwtDecode(response.user.token) + this.updateToken(response.user?.token) + const decodedToken = jwtDecode(response.user?.token) this.isLogin = true this.role = decodedToken.role }) - .catch((error) => { - if (error.status) { - code = error.status - } - }) + .catch(() => {}) return code }, @@ -70,10 +59,6 @@ export const useAuth = defineStore('auth', { inspectToken() { let token = useCookie('token').value - if (token === null) { - token = '' - } - if (token) { this.updateToken(token) const decodedToken = jwtDecode(token) @@ -84,7 +69,7 @@ export const useAuth = defineStore('auth', { if (expireToken && this.jwtToken && expireToken - timestamp > 15) { this.isLogin = true } else { - // Prompt user to re login. + // Prompt user to re-login. this.isLogin = false } } else { diff --git a/types/index.d.ts b/types/index.d.ts index c036b776..ceaea7b4 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,6 +1,22 @@ +import { type JwtPayload } from 'jwt-decode' + export {} declare global { + interface JwtPayloadExt extends JwtPayload { + role: string + } + + interface LoginObj { + message: string + user?: { + id: number + mail: string + username: string + token + } + } + interface GuiConfig { id: number config_path: string