forked from BRETT/BRETT
51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
export interface AuthUser {
|
|
id: number
|
|
name: string
|
|
email: string | null
|
|
color: string | null
|
|
cardEffect: string | null
|
|
cardEffectColor: string | null
|
|
cardVignette: boolean
|
|
cardBorderEffect: string | null
|
|
cardBorderEffectColor: string | null
|
|
avatarUrl: string | null
|
|
roles: string[]
|
|
permissions: string[]
|
|
}
|
|
|
|
export function useAuth() {
|
|
const user = useState<AuthUser | null>('auth:user', () => null)
|
|
|
|
async function refresh() {
|
|
const requestFetch = useRequestFetch()
|
|
const res = await requestFetch<{ user: AuthUser | null }>('/api/auth/me')
|
|
user.value = res.user
|
|
}
|
|
|
|
async function login(name: string, password: string) {
|
|
const res = await $fetch<{ user: AuthUser }>('/api/auth/login', {
|
|
method: 'POST',
|
|
body: { name, password },
|
|
})
|
|
user.value = res.user
|
|
}
|
|
|
|
async function register(name: string, password: string, email?: string) {
|
|
const res = await $fetch<{ user: AuthUser }>('/api/auth/register', {
|
|
method: 'POST',
|
|
body: { name, password, email },
|
|
})
|
|
user.value = res.user
|
|
}
|
|
|
|
async function logout() {
|
|
await $fetch('/api/auth/logout', { method: 'POST' })
|
|
user.value = null
|
|
}
|
|
|
|
const isAdmin = computed(() => user.value?.roles.includes('admin') ?? false)
|
|
const can = (permission: string) => isAdmin.value || (user.value?.permissions.includes(permission) ?? false)
|
|
|
|
return { user, isAdmin, can, refresh, login, register, logout }
|
|
}
|