Refactor project structure and update dependencies
This commit is contained in:
53
nuxt/app/stores/auth.ts
Normal file
53
nuxt/app/stores/auth.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { IAccountLogoutResponse } from '~/types/account'
|
||||
|
||||
export type User = {
|
||||
ulid: string
|
||||
name: string
|
||||
email: string
|
||||
avatar: string
|
||||
must_verify_email: boolean
|
||||
has_password: boolean
|
||||
roles: string[]
|
||||
providers: string[]
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const config = useRuntimeConfig()
|
||||
const nuxtApp = useNuxtApp()
|
||||
|
||||
const user = ref(<User>{})
|
||||
const token = useCookie('token', {
|
||||
path: '/',
|
||||
sameSite: 'strict',
|
||||
secure: config.public.apiBase.startsWith('https://'),
|
||||
maxAge: 60 * 60 * 24 * 365,
|
||||
})
|
||||
const isLoggedIn = computed(() => !!token.value)
|
||||
|
||||
const { refresh: logout } = useFetch<IAccountLogoutResponse>('logout', {
|
||||
method: 'POST',
|
||||
immediate: false,
|
||||
onResponse({ response }) {
|
||||
if (response.status === 200) {
|
||||
token.value = ''
|
||||
user.value = <User>{}
|
||||
|
||||
return nuxtApp.runWithContext(() => {
|
||||
return navigateTo('/')
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const { refresh: fetchUser } = useFetch<{ user: User }>('user', {
|
||||
immediate: false,
|
||||
onResponse({ response }) {
|
||||
if (response.status === 200) {
|
||||
user.value = response._data.user
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return { user, isLoggedIn, logout, fetchUser, token }
|
||||
})
|
||||
Reference in New Issue
Block a user