45 lines
1.2 KiB
TypeScript
45 lines
1.2 KiB
TypeScript
|
|
import type { AuthResult, AuthUser } from '~/types/game'
|
||
|
|
|
||
|
|
const USER_KEY = 'vp.user'
|
||
|
|
|
||
|
|
function readStoredUser(): AuthUser | null {
|
||
|
|
try {
|
||
|
|
const raw = localStorage.getItem(USER_KEY)
|
||
|
|
return raw ? JSON.parse(raw) : null
|
||
|
|
} catch {
|
||
|
|
return null
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function storeUser(user: AuthUser | null) {
|
||
|
|
try {
|
||
|
|
if (user) localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||
|
|
else localStorage.removeItem(USER_KEY)
|
||
|
|
} catch {
|
||
|
|
// the token still works; only the name in the header is lost on reload
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export function useAuth() {
|
||
|
|
const user = useState<AuthUser | null>('auth.user', () => (gameAuth.token() ? readStoredUser() : null))
|
||
|
|
|
||
|
|
function signedIn(result: AuthResult) {
|
||
|
|
user.value = result.user
|
||
|
|
storeUser(result.user)
|
||
|
|
}
|
||
|
|
|
||
|
|
return {
|
||
|
|
user,
|
||
|
|
isLoggedIn: () => gameAuth.token() !== null,
|
||
|
|
login: async (email: string, password: string) => signedIn(await gameAuth.login(email, password)),
|
||
|
|
register: async (name: string, email: string, password: string) =>
|
||
|
|
signedIn(await gameAuth.register(name, email, password)),
|
||
|
|
logout() {
|
||
|
|
gameAuth.logout()
|
||
|
|
user.value = null
|
||
|
|
storeUser(null)
|
||
|
|
return navigateTo('/login')
|
||
|
|
},
|
||
|
|
}
|
||
|
|
}
|