login.ts 2.2 KB

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