54 lines
1.6 KiB
TypeScript
54 lines
1.6 KiB
TypeScript
import { navigateTo } from "#app"
|
|
import { useUserinfoStore, Userinfo } from "@/stores/UserinfoStore"
|
|
import { $fetch } from 'ohmyfetch'
|
|
|
|
export type AllowRole = '' | 'player' | 'gamemaster' | 'admin'
|
|
export type AllowRoles = Array<AllowRole>
|
|
|
|
export interface useAuth {
|
|
login(authCode: string): Promise<void>
|
|
logout(): Promise<void>
|
|
authenticateAndLoadUserInfo(allowRoles: AllowRoles): Promise<void>
|
|
}
|
|
|
|
export default (): useAuth => {
|
|
const user = useUserinfoStore()
|
|
|
|
return {
|
|
authenticateAndLoadUserInfo: async (allowRoles: AllowRoles): Promise<void> => {
|
|
try {
|
|
const userInfo = await $fetch('/api/userinfo') as Userinfo
|
|
user.setUserInfo(userInfo)
|
|
if (allowRoles.indexOf(userInfo.role) >= 0 ) {
|
|
return
|
|
}
|
|
if (user.isAdmin) {
|
|
document.location.pathname = '/admin'
|
|
// can't use navigateTo() for it fails with DOMException if two consecutive redirects happen (at least in docker container)
|
|
// navigateTo('/admin', { replace: true })
|
|
} else {
|
|
document.location.pathname = '/play'
|
|
}
|
|
} catch (e) {
|
|
if (allowRoles.indexOf('') == -1 ) {
|
|
document.location.pathname = '/'
|
|
}
|
|
}
|
|
},
|
|
|
|
login: async (authCode: string): Promise<void> => {
|
|
if (authCode.length != 6) {
|
|
throw Error('login failed')
|
|
}
|
|
const resp = await $fetch(`/api/login?code=${authCode}`)
|
|
if (resp !== 'ok') {
|
|
throw Error('login failed')
|
|
}
|
|
},
|
|
|
|
logout: async (): Promise<void> => {
|
|
await $fetch('/api/logout')
|
|
},
|
|
}
|
|
}
|