Переглянути джерело

feat: 添加登录页面URL配置及页面权限控制

- 在.env文件中新增VITE_LOGIN_URL配置
- 在App.vue中引入并调用usePageAuth以实现页面权限控制
- 更新route.ts以使用环境变量中的登录页面URL
陈剑术 11 місяців тому
батько
коміт
dcae738e69
4 змінених файлів з 55 додано та 1 видалено
  1. 3 0
      env/.env
  2. 3 0
      src/App.vue
  3. 48 0
      src/hooks/usePageAuth.ts
  4. 1 1
      src/interceptors/route.ts

+ 3 - 0
env/.env

@@ -7,6 +7,9 @@ VITE_WX_APPID = 'wxa2abb91f64032a2b'
 # h5部署网站的base,配置到 manifest.config.ts 里的 h5.router.base
 VITE_APP_PUBLIC_BASE=/
 
+# 登录页面
+VITE_LOGIN_URL = '/pages/login/index'
+
 VITE_SERVER_BASEURL = 'https://ukw0y1.laf.run'
 VITE_UPLOAD_BASEURL = 'https://ukw0y1.laf.run/upload'
 

+ 3 - 0
src/App.vue

@@ -1,6 +1,9 @@
 <script setup lang="ts">
 import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
 import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
+import { usePageAuth } from '@/hooks/usePageAuth'
+
+usePageAuth()
 
 onLaunch(() => {
   console.log('App Launch')

+ 48 - 0
src/hooks/usePageAuth.ts

@@ -0,0 +1,48 @@
+import { onLoad } from '@dcloudio/uni-app'
+import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils'
+import { useUserStore } from '@/store'
+
+const loginRoute = import.meta.env.VITE_LOGIN_URL
+const isDev = import.meta.env.DEV
+
+// 检查当前页面是否需要登录
+export function usePageAuth() {
+  onLoad((options) => {
+    // 获取当前页面路径
+    const pages = getCurrentPages()
+    const currentPage = pages[pages.length - 1]
+    const currentPath = `/${currentPage.route}`
+
+    // 获取需要登录的页面列表
+    let needLoginPages: string[] = []
+    if (isDev) {
+      needLoginPages = getNeedLoginPages()
+    } else {
+      needLoginPages = _needLoginPages
+    }
+
+    // 检查当前页面是否需要登录
+    const isNeedLogin = needLoginPages.includes(currentPath)
+    if (!isNeedLogin) {
+      return
+    }
+
+    // 检查是否已登录
+    const userStore = useUserStore()
+    const hasLogin = userStore.isLogined
+    if (hasLogin) {
+      return
+    }
+
+    // 构建重定向URL
+    const queryString = Object.entries(options || {})
+      .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
+      .join('&')
+
+    const currentFullPath = queryString ? `${currentPath}?${queryString}` : currentPath
+    const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(currentFullPath)}`
+
+    // 重定向到登录页
+    uni.redirectTo({ url: redirectRoute })
+  })
+}

+ 1 - 1
src/interceptors/route.ts

@@ -8,7 +8,7 @@ import { useUserStore } from '@/store'
 import { needLoginPages as _needLoginPages, getNeedLoginPages, getLastPage } from '@/utils'
 
 // TODO Check
-const loginRoute = '/pages/login/index'
+const loginRoute = import.meta.env.VITE_LOGIN_URL
 
 const isLogined = () => {
   const userStore = useUserStore()