Polarcraft/webv2/middleware/auth.ts

26 lines
525 B
TypeScript
Raw Normal View History

2023-06-04 22:47:48 +02:00
export default defineNuxtRouteMiddleware(async (to) => {
if (process.server) {
return
}
try {
2023-06-06 13:49:27 +02:00
const user: IUser = await $fetch('/api/users/@me')
2023-06-04 22:47:48 +02:00
2023-06-05 14:55:35 +02:00
if (!user._id) {
2023-06-04 22:47:48 +02:00
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')
}
})