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' import { $fetch } from 'ohmyfetch' export type AllowRole = '' | 'player' | 'gamemaster' | 'admin' | 'setup' export type AllowRoles = Array export interface useAuth { login(authCode: string): Promise logout(): Promise authenticateAndLoadUserInfo(allowRoles: AllowRoles): Promise } export default (): useAuth => { const user = useUserinfoStore() return { authenticateAndLoadUserInfo: async (allowRoles: AllowRoles): Promise => { try { const userInfo = await $fetch('/api/userinfo') as Userinfo user.setUserInfo(userInfo) useI18n({}).setLang(userInfo.lang) if (allowRoles.indexOf(userInfo.role) >= 0 ) { // user is authenticated and authorized, let the user in return } // game is not initialized yet, needs setup if (userInfo.role === 'setup') { document.location.pathname = '/setup' return } // user is authenticated but not authorized for this page 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) { // user is not authenticated if (allowRoles.indexOf('') == -1 ) { document.location.pathname = '/' } } }, login: async (authCode: string): Promise => { 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 => { await $fetch('/api/logout') useEngineStore().reset() useGameinfoStore().reset() usePlayersStore().reset() useUserinfoStore().reset() useRoundStore().reset() }, } }