Files
sub2api/frontend/src/router
29a5fcd25e fix(gateway,frontend): 修复鉴权绕过与前端支付/会话缺陷
后端:
- Gemini /v1beta 鉴权中间件补齐主中间件的授权校验: API Key 的 IP 白/黑名单、
  专属分组授权、运行时过期/配额二次检查, 修复经 Gemini 端点绕过 IP ACL、
  越权访问专属分组、以及状态未刷新时的配额/有效期绕过窗口。
- 粘性会话等待计划分支改走 newSelectionResult 以 hydrate 账号凭证, 修复调度
  快照中账号凭证被剥离导致等待路径转发鉴权失败。
- SSE 流式转发客户端断开时不再 break 跳过当前事件 usage 合并, 修复少计费。
- Forward 对 nil gin.Context 的防御补齐; 上游错误体读取失败时记录日志避免静默。

前端:
- logout 将本地会话清理移入 finally, 服务端吊销失败也保证本地登出。
- Stripe 弹窗轮询改用正确的 auth_token 键并加防重入; 收到 INIT 后清除兜底
  超时定时器, onUnmounted 清理 message 监听器。
- token 刷新请求补充 30s 超时, 避免挂起导致请求队列与 loading 永久卡死。
- 路由守卫在公共设置未加载时先 await fetchPublicSettings, 避免 payment/
  risk_control 被误判为未启用而错误拦截。
- 支付状态轮询回调补充防重入与终态守卫。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-09 09:06:56 +08:00
..

Vue Router Configuration

Overview

This directory contains the Vue Router configuration for the Sub2API frontend application. The router implements a comprehensive navigation system with authentication guards, role-based access control, and lazy loading.

Files

  • index.ts: Main router configuration with route definitions and navigation guards
  • meta.d.ts: TypeScript type definitions for route meta fields

Route Structure

Public Routes (No Authentication Required)

Path Component Description
/login LoginView User login page
/register RegisterView User registration page

User Routes (Authentication Required)

Path Component Description
/ - Redirects to /dashboard
/dashboard DashboardView User dashboard with stats
/keys KeysView API key management
/usage UsageView Usage records and statistics
/redeem RedeemView Redeem code interface
/profile ProfileView User profile settings

Admin Routes (Admin Role Required)

Path Component Description
/admin - Redirects to /admin/dashboard
/admin/dashboard AdminDashboardView Admin dashboard
/admin/users AdminUsersView User management
/admin/groups AdminGroupsView Group management
/admin/accounts AdminAccountsView Account management
/admin/proxies AdminProxiesView Proxy management
/admin/redeem AdminRedeemView Redeem code management

Special Routes

Path Component Description
/:pathMatch(.*) NotFoundView 404 error page

Navigation Guards

Authentication Guard (beforeEach)

The router implements a comprehensive navigation guard that:

  1. Sets Page Title: Updates document title based on route meta
  2. Checks Authentication:
    • Public routes (requiresAuth: false) are accessible without login
    • Protected routes require authentication
    • Redirects to /login if not authenticated
  3. Prevents Double Login:
    • Redirects authenticated users away from login/register pages
  4. Role-Based Access Control:
    • Admin routes (requiresAdmin: true) require admin role
    • Non-admin users are redirected to /dashboard
  5. Preserves Intended Destination:
    • Saves original URL in query parameter for post-login redirect

Flow Diagram

User navigates to route
        ↓
Set page title from meta
        ↓
Is route public? ──Yes──→ Already authenticated? ──Yes──→ Redirect to /dashboard
        ↓ No                                        ↓ No
        ↓                                      Allow access
        ↓
Is user authenticated? ──No──→ Redirect to /login with redirect query
        ↓ Yes
        ↓
Requires admin role? ──Yes──→ Is user admin? ──No──→ Redirect to /dashboard
        ↓ No                                  ↓ Yes
        ↓                                     ↓
Allow access ←────────────────────────────────┘

Route Meta Fields

Each route can define the following meta fields:

interface RouteMeta {
  requiresAuth?: boolean // Default: true (requires authentication)
  requiresAdmin?: boolean // Default: false (admin access only)
  title?: string // Page title
  breadcrumbs?: Array<{
    // Breadcrumb navigation
    label: string
    to?: string
  }>
  icon?: string // Icon for navigation menu
  hideInMenu?: boolean // Hide from navigation menu
}

Lazy Loading

All route components use dynamic imports for code splitting:

component: () => import('@/views/user/DashboardView.vue')

Benefits:

  • Reduced initial bundle size
  • Faster initial page load
  • Components loaded on-demand
  • Automatic code splitting by Vite

Authentication Store Integration

The router integrates with the Pinia auth store (@/stores/auth):

const authStore = useAuthStore()

// Check authentication status
authStore.isAuthenticated

// Check admin role
authStore.isAdmin

Usage Examples

Programmatic Navigation

import { useRouter } from 'vue-router'

const router = useRouter()

// Navigate to a route
router.push('/dashboard')

// Navigate with query parameters
router.push({
  path: '/usage',
  query: { filter: 'today' }
})

// Navigate to admin route (will be blocked if not admin)
router.push('/admin/users')
<template>
  <!-- Simple link -->
  <router-link to="/dashboard">Dashboard</router-link>

  <!-- Named route -->
  <router-link :to="{ name: 'Keys' }">API Keys</router-link>

  <!-- With query parameters -->
  <router-link :to="{ path: '/usage', query: { page: 1 } }"> Usage </router-link>
</template>

Checking Current Route

import { useRoute } from 'vue-router'

const route = useRoute()

// Check if on admin page
const isAdminPage = route.path.startsWith('/admin')

// Get route meta
const requiresAdmin = route.meta.requiresAdmin

Scroll Behavior

The router implements automatic scroll management:

  • Browser Navigation: Restores saved scroll position
  • New Routes: Scrolls to top of page
  • Hash Links: Scrolls to anchor (when implemented)

Error Handling

The router includes error handling for navigation failures:

router.onError((error) => {
  console.error('Router error:', error)
})

Testing Routes

To test navigation guards and route access:

  1. Public Route Access: Visit /login without authentication
  2. Protected Route: Try accessing /dashboard without login (should redirect)
  3. Admin Access: Login as regular user, try /admin/users (should redirect to dashboard)
  4. Admin Success: Login as admin, access /admin/users (should succeed)
  5. 404 Handling: Visit non-existent route (should show 404 page)

Development Tips

Adding New Routes

  1. Add route definition in routes array
  2. Create corresponding view component
  3. Set appropriate meta fields (requiresAuth, requiresAdmin)
  4. Use lazy loading with () => import()
  5. Update this README with route documentation

Debugging Navigation

Enable Vue Router debug mode:

// In browser console
window.__VUE_ROUTER__ = router

// Check current route
router.currentRoute.value

Common Issues

Issue: 404 on page refresh

  • Cause: Server not configured for SPA
  • Solution: Configure server to serve index.html for all routes

Issue: Navigation guard runs twice

  • Cause: Multiple next() calls
  • Solution: Ensure only one next() call per code path

Issue: User data not loaded

  • Cause: Auth store not initialized
  • Solution: Call authStore.checkAuth() in App.vue or main.ts

Security Considerations

  1. Client-Side Only: Navigation guards are client-side; server must also validate
  2. Token Validation: API should verify JWT token on every request
  3. Role Checking: Backend must verify admin role, not just frontend
  4. XSS Protection: Vue automatically escapes template content
  5. CSRF Protection: Use CSRF tokens for state-changing operations

Performance Optimization

  1. Lazy Loading: All routes use dynamic imports
  2. Code Splitting: Vite automatically splits route chunks
  3. Prefetching: Consider adding route prefetch for common paths
  4. Route Caching: Vue Router caches component instances

Future Enhancements

  • Add breadcrumb navigation system
  • Implement route-based permissions beyond admin/user
  • Add route transition animations
  • Implement route prefetching for anticipated navigation
  • Add navigation analytics tracking