Bläddra i källkod

Update authentication flow and redirect handling in login process

- Disabled debug mode in the Nuxt configuration for production readiness.
- Enhanced the global authentication middleware to include a redirect query parameter when navigating to the login page.
- Updated the login page to handle redirection after successful authentication, ensuring users are returned to their intended destination.
- Improved error handling in the request utility to include redirect logic upon login expiration.
0es 4 månader sedan
förälder
incheckning
e8b4b989db
4 ändrade filer med 31 tillägg och 4 borttagningar
  1. 6 1
      app/middleware/auth.global.ts
  2. 17 1
      app/pages/login.vue
  3. 7 1
      app/utils/request.ts
  4. 1 1
      nuxt.config.ts

+ 6 - 1
app/middleware/auth.global.ts

@@ -10,6 +10,11 @@ export default defineNuxtRouteMiddleware((to, _from) => {
 
   // If user is not authenticated, redirect to login
   if (isInitialized.value && !isAuthenticated.value) {
-    return navigateTo('/login')
+    const redirect = to.fullPath
+
+    return navigateTo({
+      path: '/login',
+      query: redirect && redirect !== '/login' ? { redirect } : undefined,
+    })
   }
 })

+ 17 - 1
app/pages/login.vue

@@ -10,11 +10,27 @@ definePageMeta({
 })
 
 const router = useRouter()
+const route = useRoute()
 const { login, loginWithEmail, isAuthenticated } = useAuth()
 const config = useRuntimeConfig()
 
 const isTestEnv = computed(() => config.public.env === 'development')
 
+const redirectPath = computed(() => {
+  const redirect = route.query.redirect
+
+  if (!redirect || Array.isArray(redirect)) {
+    return '/'
+  }
+
+  // 避免跳转回登录页本身
+  if (typeof redirect === 'string' && redirect.startsWith('/login')) {
+    return '/'
+  }
+
+  return redirect as string
+})
+
 const showTestLogin = ref(false)
 const testEmail = ref('')
 const testLoginLoading = ref(false)
@@ -23,7 +39,7 @@ const testLoginError = ref('')
 onMounted(() => {
   watch(isAuthenticated, (newIsAuthenticated) => {
     if (newIsAuthenticated) {
-      router.push('/')
+      router.replace(redirectPath.value)
     }
   })
 })

+ 7 - 1
app/utils/request.ts

@@ -253,8 +253,14 @@ export const createRequest = () => {
 
     // Redirect to login page
     if (import.meta.client) {
+      const route = useRoute()
+      const redirect = route.fullPath
+
       showError('Login expired, please login again')
-      navigateTo('/login')
+      navigateTo({
+        path: '/login',
+        query: redirect && redirect !== '/login' ? { redirect } : undefined,
+      })
     }
   }
 

+ 1 - 1
nuxt.config.ts

@@ -52,7 +52,7 @@ export default defineNuxtConfig({
       },
     },
   },
-  debug: true,
+  debug: false,
   eslint: {
     config: {
       stylistic: true,