Polarcraft/webv2/middleware/auth.ts

26 lines
525 B
TypeScript

export default defineNuxtRouteMiddleware(async (to) => {
if (process.server) {
return
}
try {
const user: IUser = await $fetch('/api/users/@me')
if (!user._id) {
throw createError({ statusCode: 500, statusMessage: 'No user was found' })
}
useState('user', () => user)
if (to.meta.moderator && !user.role.moderator) {
return navigateTo('/')
}
} catch (e) {
console.error('Failed to get user', e)
useState('user', () => null)
return navigateTo('/login')
}
})