login.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { stringify } from 'querystring';
  2. import type { Reducer, Effect } from 'umi';
  3. import { history } from 'umi';
  4. import { fakeAccountLogin } from '@/services/login';
  5. import { setAuthority } from '@/utils/authority';
  6. import { getPageQuery } from '@/utils/utils';
  7. import { message } from 'antd';
  8. export type StateType = {
  9. status?: 'ok' | 'error';
  10. type?: string;
  11. currentAuthority?: 'user' | 'guest' | 'admin';
  12. };
  13. export type LoginModelType = {
  14. namespace: string;
  15. state: StateType;
  16. effects: {
  17. login: Effect;
  18. logout: Effect;
  19. };
  20. reducers: {
  21. changeLoginStatus: Reducer<StateType>;
  22. };
  23. };
  24. const Model: LoginModelType = {
  25. namespace: 'login',
  26. state: {
  27. status: undefined,
  28. },
  29. effects: {
  30. *login({ payload }, { call, put }) {
  31. const response = yield call(fakeAccountLogin, payload);
  32. yield put({
  33. type: 'changeLoginStatus',
  34. payload: response,
  35. });
  36. // Login successfully
  37. if (response.status === 'ok') {
  38. const urlParams = new URL(window.location.href);
  39. const params = getPageQuery();
  40. message.success('🎉 🎉 🎉 登录成功!');
  41. let { redirect } = params as { redirect: string };
  42. if (redirect) {
  43. const redirectUrlParams = new URL(redirect);
  44. if (redirectUrlParams.origin === urlParams.origin) {
  45. redirect = redirect.substr(urlParams.origin.length);
  46. if (window.routerBase !== '/') {
  47. redirect = redirect.replace(window.routerBase, '/');
  48. }
  49. if (redirect.match(/^\/.*#/)) {
  50. redirect = redirect.substr(redirect.indexOf('#') + 1);
  51. }
  52. } else {
  53. window.location.href = '/';
  54. return;
  55. }
  56. }
  57. history.replace(redirect || '/');
  58. }
  59. },
  60. logout() {
  61. const { redirect } = getPageQuery();
  62. // Note: There may be security issues, please note
  63. if (window.location.pathname !== '/user/login' && !redirect) {
  64. history.replace({
  65. pathname: '/user/login',
  66. search: stringify({
  67. redirect: window.location.href,
  68. }),
  69. });
  70. }
  71. },
  72. },
  73. reducers: {
  74. changeLoginStatus(state, { payload }) {
  75. setAuthority(payload.currentAuthority);
  76. return {
  77. ...state,
  78. status: payload.status,
  79. type: payload.type,
  80. };
  81. },
  82. },
  83. };
  84. export default Model;