auth.tsx 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { defineComponent } from 'vue'
  2. import styles from './index.module.less'
  3. import { state, setLogin, setLogout, setLoginError } from '@/state'
  4. import { browser } from '@/helpers/utils'
  5. import { setAuth } from './utils'
  6. import { RouterView } from 'vue-router'
  7. import OEmpty from '@/components/o-empty'
  8. import request from '@/helpers/request'
  9. const browserInfo = browser()
  10. export default defineComponent({
  11. name: 'Auth-loayout',
  12. data() {
  13. return {
  14. loading: false as boolean
  15. }
  16. },
  17. computed: {
  18. isExternal() {
  19. // 该路由在外部连接打开是否需要登录
  20. // 只判断是否在学生端打开
  21. return (this.$route.meta.isExternal && !browserInfo.isStudent) || false
  22. },
  23. isNeedView() {
  24. return (
  25. state.user.status === 'login' ||
  26. this.$route.path === '/loginMusic' ||
  27. (this as any).isExternal
  28. )
  29. }
  30. },
  31. mounted() {
  32. !this.isExternal && this.setAuth()
  33. },
  34. methods: {
  35. async setAuth() {
  36. const { query } = this.$route
  37. const token = query.userInfo || query.Authorization
  38. if (token) {
  39. setAuth(token)
  40. }
  41. if (this.loading) {
  42. return
  43. }
  44. if (state.user.status === 'init' || state.user.status === 'error') {
  45. this.loading = true
  46. try {
  47. const res = await request.get('/api-student/appLoginUser/getUserInfo', {
  48. initRequest: true, // 初始化接口
  49. requestType: 'form'
  50. })
  51. setLogin(res.data)
  52. } catch (e: any) {
  53. // console.log(e, 'e')
  54. const message = e.message
  55. if (message.indexOf('5000') === -1 && message.indexOf('authentication') === -1) {
  56. setLoginError()
  57. } else {
  58. setLogout()
  59. }
  60. }
  61. this.loading = false
  62. }
  63. if (state.user.status === 'logout') {
  64. try {
  65. const route = this.$route
  66. const query = {
  67. returnUrl: this.$route.path,
  68. ...this.$route.query
  69. } as any
  70. if (route.meta.isRegister) {
  71. query.isRegister = route.meta.isRegister
  72. }
  73. this.$router.replace({
  74. path: '/loginMusic',
  75. query: query
  76. })
  77. } catch (error) {
  78. //
  79. }
  80. }
  81. }
  82. },
  83. render() {
  84. return (
  85. <>
  86. {state.user.status === 'error' ? (
  87. <div class={styles.error}>
  88. <OEmpty
  89. type="notFond"
  90. classImgSize="CERT"
  91. tips="加载失败,请稍后重试"
  92. buttonText="重新加载"
  93. plain={true}
  94. btnStatus={true}
  95. onClick={this.setAuth}
  96. />
  97. </div>
  98. ) : this.isNeedView ? (
  99. <RouterView></RouterView>
  100. ) : null}
  101. </>
  102. )
  103. }
  104. })