西藏巴青项目

apiAuth.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { getToken } from '@/utils/auth'
  2. import { getStoredLocale } from '@/utils/locale'
  3. import zh from '@/locale/zh'
  4. import bo from '@/locale/bo'
  5. const LOGIN_URL = '/pages/login/index'
  6. /** 避免连续触发多次跳转登录页 */
  7. let loginRedirecting = false
  8. function apiAuthMsg() {
  9. const locale = getStoredLocale()
  10. const pack = locale === 'bo' ? bo : zh
  11. return (pack.apiAuth && pack.apiAuth.needLogin) || '请先登录'
  12. }
  13. function redirectToLoginPage() {
  14. if (loginRedirecting) return
  15. loginRedirecting = true
  16. setTimeout(() => {
  17. loginRedirecting = false
  18. }, 2000)
  19. uni.navigateTo({
  20. url: LOGIN_URL,
  21. fail: () => {
  22. uni.reLaunch({ url: LOGIN_URL })
  23. }
  24. })
  25. }
  26. /**
  27. * 调用需登录的接口前校验 Token
  28. * @returns {boolean} 有 Token 返回 true,否则提示并跳转登录页
  29. */
  30. export function ensureApiToken(showToast = true) {
  31. if (getToken()) {
  32. return true
  33. }
  34. if (showToast) {
  35. uni.showToast({
  36. title: apiAuthMsg(),
  37. icon: 'none',
  38. duration: 1500
  39. })
  40. setTimeout(() => redirectToLoginPage(), 400)
  41. }
  42. return false
  43. }
  44. /**
  45. * 包装需登录的接口请求:无 Token 时直接 reject,不发起请求
  46. */
  47. export function callAuthApi(apiFn) {
  48. if (!ensureApiToken()) {
  49. return Promise.reject(new Error('未登录'))
  50. }
  51. return apiFn()
  52. }