login.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { routerRedux } from 'dva/router';
  2. import { stringify } from 'qs';
  3. import { fakeAccountLogin, getFakeCaptcha } from '../services/api';
  4. import { setAuthority } from '../utils/authority';
  5. import { getPageQuery } from '../utils/utils';
  6. import { reloadAuthorized } from '../utils/Authorized';
  7. export default {
  8. namespace: 'login',
  9. state: {
  10. status: undefined,
  11. },
  12. effects: {
  13. *login({ payload }, { call, put }) {
  14. const response = yield call(fakeAccountLogin, payload);
  15. yield put({
  16. type: 'changeLoginStatus',
  17. payload: response,
  18. });
  19. // Login successfully
  20. if (response.status === 'ok') {
  21. reloadAuthorized();
  22. const urlParams = new URL(window.location.href);
  23. const params = getPageQuery();
  24. let { redirect } = params;
  25. if (redirect) {
  26. const redirectUrlParams = new URL(redirect);
  27. if (redirectUrlParams.origin === urlParams.origin) {
  28. redirect = redirect.substr(urlParams.origin.length);
  29. if (redirect.startsWith('/#')) {
  30. redirect = redirect.substr(2);
  31. }
  32. } else {
  33. window.location.href = redirect;
  34. return;
  35. }
  36. }
  37. yield put(routerRedux.replace(redirect || '/'));
  38. }
  39. },
  40. *getCaptcha({ payload }, { call }) {
  41. yield call(getFakeCaptcha, payload);
  42. },
  43. *logout(_, { put }) {
  44. yield put({
  45. type: 'changeLoginStatus',
  46. payload: {
  47. status: false,
  48. currentAuthority: 'guest',
  49. },
  50. });
  51. reloadAuthorized();
  52. yield put(
  53. routerRedux.push({
  54. pathname: '/user/login',
  55. search: stringify({
  56. redirect: window.location.href,
  57. }),
  58. })
  59. );
  60. },
  61. },
  62. reducers: {
  63. changeLoginStatus(state, { payload }) {
  64. setAuthority(payload.currentAuthority);
  65. return {
  66. ...state,
  67. status: payload.status,
  68. type: payload.type,
  69. };
  70. },
  71. },
  72. };