Polarcraft/webv2/middleware/auth.js
2023-06-05 14:55:35 +02:00

26 lines
518 B
JavaScript

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