usePageAuth.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { onLoad } from '@dcloudio/uni-app'
  2. import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils'
  3. import { useUserStore } from '@/store'
  4. const loginRoute = import.meta.env.VITE_LOGIN_URL
  5. const isDev = import.meta.env.DEV
  6. const 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. } else {
  22. needLoginPages = _needLoginPages
  23. }
  24. // 检查当前页面是否需要登录
  25. const isNeedLogin = needLoginPages.includes(currentPath)
  26. if (!isNeedLogin) {
  27. return
  28. }
  29. const hasLogin = isLogined()
  30. if (hasLogin) {
  31. return true
  32. }
  33. // 构建重定向URL
  34. const queryString = Object.entries(options || {})
  35. .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
  36. .join('&')
  37. const currentFullPath = queryString ? `${currentPath}?${queryString}` : currentPath
  38. const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(currentFullPath)}`
  39. // 重定向到登录页
  40. uni.redirectTo({ url: redirectRoute })
  41. })
  42. }