knowyt/client/src/composables/useAuth.ts

64 lines
2.0 KiB
TypeScript
Raw Normal View History

import { useUserinfoStore, Userinfo } from '@/stores/UserinfoStore'
import { useEngineStore } from '@/stores/EngineStore'
import { useGameinfoStore } from '@/stores/GameinfoStore'
import { usePlayersStore } from '@/stores/PlayersStore'
import { useRoundStore } from '@/stores/RoundStore'
import useI18n from './useI18n'
2022-07-31 20:56:53 +00:00
import { $fetch } from 'ohmyfetch'
export type AllowRole = '' | 'player' | 'gamemaster' | 'admin'
export type AllowRoles = Array<AllowRole>
2022-07-29 13:08:12 +00:00
export interface useAuth {
login(authCode: string): Promise<void>
logout(): Promise<void>
authenticateAndLoadUserInfo(allowRoles: AllowRoles): Promise<void>
2022-07-29 13:08:12 +00:00
}
2022-07-31 20:56:53 +00:00
export default (): useAuth => {
const user = useUserinfoStore()
2022-07-29 13:08:12 +00:00
return {
authenticateAndLoadUserInfo: async (allowRoles: AllowRoles): Promise<void> => {
try {
const userInfo = await $fetch('/api/userinfo') as Userinfo
user.setUserInfo(userInfo)
useI18n({}).setLang(userInfo.lang)
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) {
2022-07-29 13:08:12 +00:00
throw Error('login failed')
}
const resp = await $fetch(`/api/login?code=${authCode}`)
2022-07-29 13:08:12 +00:00
if (resp !== 'ok') {
throw Error('login failed')
}
},
logout: async (): Promise<void> => {
await $fetch('/api/logout')
useEngineStore().reset()
useGameinfoStore().reset()
usePlayersStore().reset()
useUserinfoStore().reset()
useRoundStore().reset()
},
2022-07-29 13:08:12 +00:00
}
}