diff --git a/app/middleware/require-auth.ts b/app/middleware/require-auth.ts new file mode 100644 index 0000000..0859a5e --- /dev/null +++ b/app/middleware/require-auth.ts @@ -0,0 +1,21 @@ +import { defineNuxtRouteMiddleware, navigateTo } from '#app' +import { useAuthStore } from '~/stores/auth' + +export default defineNuxtRouteMiddleware(async (to) => { + const auth = useAuthStore() + + if (!auth.accessToken) { + await auth.tryRefresh().catch(() => false) + } + + if (!auth.initialized) { + await auth.fetchUser().catch(() => null) + } else if (!auth.user) { + await auth.fetchUser().catch(() => null) + } + + if (!auth.user) { + const redirect = encodeURIComponent(to.fullPath || '/') + return navigateTo(`/login?redirect=${redirect}`) + } +}) diff --git a/app/pages/learn.vue b/app/pages/learn.vue index 2502c45..8c7359c 100644 --- a/app/pages/learn.vue +++ b/app/pages/learn.vue @@ -413,8 +413,12 @@