41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
import type { UserSession, UserSessionComposable } from '~/types/auth'
|
|
import { useContent } from './useContent'
|
|
|
|
const useSessionState = () => useState<UserSession>('nuxt-session', () => ({}))
|
|
const useAuthReadyState = () => useState('nuxt-auth-ready', () => false)
|
|
const useContentFetch = (force: boolean) => useContent().fetch(force);
|
|
|
|
/**
|
|
* Composable to get back the user session and utils around it.
|
|
* @see https://github.com/atinux/nuxt-auth-utils
|
|
*/
|
|
export function useUserSession(): UserSessionComposable {
|
|
const sessionState = useSessionState()
|
|
const authReadyState = useAuthReadyState()
|
|
return {
|
|
ready: computed(() => authReadyState.value),
|
|
loggedIn: computed(() => Boolean(sessionState.value.user)),
|
|
user: computed(() => sessionState.value.user ?? null),
|
|
session: sessionState,
|
|
fetch,
|
|
clear,
|
|
}
|
|
}
|
|
|
|
async function fetch(): Promise<boolean> {
|
|
const authReadyState = useAuthReadyState()
|
|
const sessionState = useSessionState()
|
|
const loggedIn = Boolean(sessionState.value.user)
|
|
sessionState.value = await useRequestFetch()('/api/auth/session').catch(() => ({}))
|
|
if (!authReadyState.value)
|
|
{
|
|
authReadyState.value = true
|
|
}
|
|
return loggedIn !== Boolean(sessionState.value.user);
|
|
}
|
|
|
|
async function clear() {
|
|
await useRequestFetch()('/api/auth/session', { method: 'DELETE' })
|
|
useSessionState().value = {}
|
|
useRouter().go(0)
|
|
} |