Răsfoiți Sursa

fixd: 优化mobile端路由守卫异常

ice-static 4 luni în urmă
părinte
comite
40d32cebfd

+ 1 - 0
frontend/src/app/mobile/app-mobile.routes.ts

@@ -10,6 +10,7 @@ export const mobileRoutes: Routes = [
     loadComponent: () => import('./layouts/mobile-layout/mobile-layout')
       .then(m => m.MobileLayout),
     canActivate: [AuthGuard],
+    canActivateChild: [AuthGuard],
     children: [
       { path: '', redirectTo: 'home', pathMatch: 'full' },
       { path: 'home', loadComponent: () => import('./features/home/home/home').then(m => m.Home) },

+ 21 - 10
frontend/src/app/mobile/core/guards/auth.guard.ts

@@ -1,32 +1,43 @@
 import { Injectable, inject } from '@angular/core';
-import { CanActivate, Router, UrlTree, ActivatedRouteSnapshot } from '@angular/router';
+import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
 import { MSQParse } from '../parse';
 import { SessionService } from '../services/session.service';
 
 @Injectable({ providedIn: 'root' })
-export class AuthGuard implements CanActivate {
+export class AuthGuard implements CanActivate, CanActivateChild {
 
   private readonly router = inject(Router);
   private readonly sessionService = inject(SessionService);
 
-  async canActivate(route: ActivatedRouteSnapshot): Promise<boolean | UrlTree> {
-    const isLoginPage = route.routeConfig?.path === 'login';
+  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> {
+    return this.canActivate(route, state);
+  }
+
+  async canActivate(route: ActivatedRouteSnapshot, _state: RouterStateSnapshot): Promise<boolean | UrlTree> {
+    const path = route.routeConfig?.path;
+    const isPublicPage = path === 'login' || path === 'register';
 
     // 先检查 session 是否过期
     if (this.sessionService.checkExpired()) {
       this.sessionService.clear();
-      if (isLoginPage) {
+      try {
+        if (MSQParse.User.current()) {
+          await MSQParse.User.logOut();
+        }
+      } catch {
+      }
+      if (isPublicPage) {
         return true;
       }
-      return this.router.createUrlTree(['/login']);
+      return this.router.createUrlTree(['/mobile/login']);
     }
 
     // 检查 Parse 本地登录态
     try {
       const user = MSQParse.User.current();
       if (user) {
-        if (isLoginPage) {
-          return this.router.createUrlTree(['/home']);
+        if (isPublicPage) {
+          return this.router.createUrlTree(['/mobile/home']);
         }
         return true;
       }
@@ -34,9 +45,9 @@ export class AuthGuard implements CanActivate {
       // 检查失败,视为未登录
     }
 
-    if (isLoginPage) {
+    if (isPublicPage) {
       return true;
     }
-    return this.router.createUrlTree(['/login']);
+    return this.router.createUrlTree(['/mobile/login']);
   }
 }