Polarcraft/webv2/middleware/auth.js
2023-06-04 22:47:48 +02:00

26 lines
517 B
JavaScript

export default defineNuxtRouteMiddleware(async (to) => {
if (process.server) {
return
}
try {
const user = await $fetch('/api/auth/user')
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')
}
})