From 0628a09749df792f7f5e3427c5cb496dc3ca0ccb Mon Sep 17 00:00:00 2001 From: axolotle Date: Wed, 26 Jul 2023 05:24:04 +0200 Subject: [PATCH] add redirect after login --- composables/states.ts | 2 ++ middleware/auth.global.ts | 11 ++++++++--- pages/login.vue | 6 ++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/composables/states.ts b/composables/states.ts index f2f1cac..86480fb 100644 --- a/composables/states.ts +++ b/composables/states.ts @@ -1 +1,3 @@ export const useIsLoggedIn = () => useState('isLoggedIn', () => false) +export const useRedirectUrl = () => + useState('redirectUrl', () => null) diff --git a/middleware/auth.global.ts b/middleware/auth.global.ts index 0bc27c8..07a7f56 100644 --- a/middleware/auth.global.ts +++ b/middleware/auth.global.ts @@ -1,12 +1,17 @@ -import { useIsLoggedIn } from '@/composables/states' +import { useIsLoggedIn, useRedirectUrl } from '@/composables/states' export default defineNuxtRouteMiddleware((to, from) => { const isLoggedIn = useIsLoggedIn() + useRedirectUrl().value = (from.query.r as string) || null + if (useRedirectUrl().value && to.name === 'login') { + to.query.r = useRedirectUrl().value + } + if (to.name === 'login' && isLoggedIn.value) { return navigateTo('/') } - if (!isLoggedIn.value) { - navigateTo('/login') + if (to.name !== 'login' && !isLoggedIn.value) { + return navigateTo('/login') } }) diff --git a/pages/login.vue b/pages/login.vue index 87d52a1..d2ed808 100644 --- a/pages/login.vue +++ b/pages/login.vue @@ -19,6 +19,12 @@ async function login(form) { }) if (!error.value) { + const redirectUrl = useRedirectUrl().value + + if (redirectUrl) { + await navigateTo(atob(redirectUrl), { external: true }) + } + isLoggedIn.value = true await navigateTo('/') } else {