auth.tsx 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { defineComponent } from 'vue';
  2. import styles from './index.module.less';
  3. import { state, setLogin, setLogout, setLoginError } from '@/state';
  4. import { useStudentRegisterStore } from '@/store/modules/student-register-store';
  5. import { RouterView } from 'vue-router';
  6. import { storage } from '@/helpers/storage';
  7. import { ACCESS_TOKEN } from '@/store/mutation-types';
  8. import OEmpty from '@/components/m-empty';
  9. import request from '@/helpers/request';
  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 || false;
  22. },
  23. isNeedView() {
  24. return (
  25. state.user.status === 'login' ||
  26. this.$route.path === '/student-register' ||
  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. storage.set(ACCESS_TOKEN, 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('/edu-app/user/getUserInfo', {
  48. initRequest: true, // 初始化接口
  49. requestType: 'form'
  50. });
  51. setLogin(res.data);
  52. } catch (e: any) {
  53. const message = e.message;
  54. if (
  55. message.indexOf('5000') === -1 &&
  56. message.indexOf('authentication') === -1
  57. ) {
  58. setLoginError();
  59. } else {
  60. setLogout();
  61. }
  62. }
  63. this.loading = false;
  64. }
  65. if (state.user.status === 'logout') {
  66. try {
  67. const studentRegisterStore = useStudentRegisterStore();
  68. const route = this.$route;
  69. const query = {
  70. sId: studentRegisterStore.getSchoolId,
  71. // returnUrl: this.$route.path,
  72. ...this.$route.query
  73. } as any;
  74. if (route.meta.isRegister) {
  75. query.isRegister = route.meta.isRegister;
  76. }
  77. this.$router.replace({
  78. path: '/student-register',
  79. query: query
  80. });
  81. } catch (error) {
  82. //
  83. }
  84. }
  85. }
  86. },
  87. render() {
  88. return (
  89. <>
  90. {state.user.status === 'error' ? (
  91. <div class={styles.error}>
  92. <OEmpty
  93. description="加载失败,请稍后重试"
  94. buttonText="重新加载"
  95. showButton
  96. onClick={this.setAuth}
  97. />
  98. </div>
  99. ) : this.isNeedView ? (
  100. <RouterView></RouterView>
  101. ) : null}
  102. </>
  103. );
  104. }
  105. });