usePageAuth.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { onLoad } from '@dcloudio/uni-app'
  2. import { useUserStore } from '@/store'
  3. import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils'
  4. const loginRoute = import.meta.env.VITE_LOGIN_URL
  5. const isDev = import.meta.env.DEV
  6. function isLogined() {
  7. const userStore = useUserStore()
  8. return !!userStore.userInfo.username
  9. }
  10. // 检查当前页面是否需要登录
  11. export function usePageAuth() {
  12. onLoad((options) => {
  13. // 获取当前页面路径
  14. const pages = getCurrentPages()
  15. const currentPage = pages[pages.length - 1]
  16. const currentPath = `/${currentPage.route}`
  17. // 获取需要登录的页面列表
  18. let needLoginPages: string[] = []
  19. if (isDev) {
  20. needLoginPages = getNeedLoginPages()
  21. }
  22. else {
  23. needLoginPages = _needLoginPages
  24. }
  25. // 检查当前页面是否需要登录
  26. const isNeedLogin = needLoginPages.includes(currentPath)
  27. if (!isNeedLogin) {
  28. return
  29. }
  30. const hasLogin = isLogined()
  31. if (hasLogin) {
  32. return true
  33. }
  34. // 构建重定向URL
  35. const queryString = Object.entries(options || {})
  36. .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
  37. .join('&')
  38. const currentFullPath = queryString ? `${currentPath}?${queryString}` : currentPath
  39. const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(currentFullPath)}`
  40. // 重定向到登录页
  41. uni.redirectTo({ url: redirectRoute })
  42. })
  43. }