login.js 1.96 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import { routerRedux } from 'dva/router';
2
import { stringify } from 'qs';
sorrycc's avatar
sorrycc committed
3 4 5 6
import { fakeAccountLogin, getFakeCaptcha } from '@/services/api';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
7 8 9 10 11 12 13 14 15

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
afc163's avatar
afc163 committed
16
    *login({ payload }, { call, put }) {
ddcat1115's avatar
ddcat1115 committed
17
      const response = yield call(fakeAccountLogin, payload);
18
      yield put({
19
        type: 'changeLoginStatus',
20 21
        payload: response,
      });
afc163's avatar
afc163 committed
22 23
      // Login successfully
      if (response.status === 'ok') {
陈帅's avatar
陈帅 committed
24
        reloadAuthorized();
25
        const urlParams = new URL(window.location.href);
yoyo837's avatar
yoyo837 committed
26 27
        const params = getPageQuery();
        let { redirect } = params;
28 29 30 31
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
32
            if (redirect.match(/^\/.*#/)) {
xiaoiver's avatar
xiaoiver committed
33
              redirect = redirect.substr(redirect.indexOf('#') + 1);
yoyo837's avatar
yoyo837 committed
34
            }
35
          } else {
36
            redirect = null;
37 38
          }
        }
39
        yield put(routerRedux.replace(redirect || '/'));
40
      }
ddcat1115's avatar
fix #52  
ddcat1115 committed
41
    },
陈帅's avatar
陈帅 committed
42

43 44 45
    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
陈帅's avatar
陈帅 committed
46

47 48 49 50 51 52 53 54 55 56
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
57
        routerRedux.replace({
58 59
          pathname: '/user/login',
          search: stringify({
60
            redirect: window.location.href,
61 62
          }),
        })
63
      );
ddcat1115's avatar
fix #52  
ddcat1115 committed
64
    },
65 66 67
  },

  reducers: {
68
    changeLoginStatus(state, { payload }) {
ddcat1115's avatar
ddcat1115 committed
69
      setAuthority(payload.currentAuthority);
70 71 72 73 74 75 76 77
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};