login.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. export interface StateType {
  7. status?: 'SUCCESS' | 'error';
  8. type?: string;
  9. currentAuthority?: '2' | '1'; // 1是管理员 ,2 是普通成员
  10. }
  11. export interface LoginModelType {
  12. namespace: string;
  13. state: StateType;
  14. effects: {
  15. login: Effect;
  16. logout: Effect;
  17. };
  18. reducers: {
  19. changeLoginStatus: Reducer<StateType>;
  20. };
  21. }
  22. const Model: LoginModelType = {
  23. namespace: 'login',
  24. state: {
  25. status: undefined,
  26. },
  27. effects: {
  28. * login({payload}, {call, put}) {
  29. // 登录
  30. const response = yield call(fakeAccountLogin, payload);
  31. // 保存登录信息,无论成功和失败
  32. localStorage.setItem("success", response.message);
  33. yield put({
  34. type: 'changeLoginStatus',
  35. payload: response,
  36. });
  37. if (response.success) {
  38. // 是否需要跳转
  39. const urlParams = new URL(window.location.href);
  40. const params = getPageQuery();
  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 (redirect.match(/^\/.*#/)) {
  47. redirect = redirect.substr(redirect.indexOf('#') + 1);
  48. }
  49. } else {
  50. window.location.href = '/';
  51. return;
  52. }
  53. }
  54. history.replace(redirect || '/');
  55. }
  56. },
  57. logout() {
  58. localStorage.removeItem("success");
  59. const {redirect} = getPageQuery();
  60. // Note: There may be security issues, please note
  61. if (window.location.pathname !== '/user/login' && !redirect) {
  62. history.replace({
  63. pathname: '/user/login',
  64. search: stringify({
  65. redirect: window.location.href,
  66. }),
  67. });
  68. }
  69. },
  70. },
  71. reducers: {
  72. changeLoginStatus(state, {payload}) {
  73. setAuthority(payload.data.roleId);
  74. return {
  75. ...state,
  76. status: payload.message,
  77. type: payload.type,
  78. };
  79. },
  80. },
  81. };
  82. export default Model;