login.js 1.97 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import { routerRedux } from 'dva/router';
2
import { stringify } from 'qs';
3
import { fakeAccountLogin, getFakeCaptcha } from '../services/api';
ddcat1115's avatar
ddcat1115 committed
4
import { setAuthority } from '../utils/authority';
5
import { getPageQuery } from '../utils/utils';
陈帅's avatar
陈帅 committed
6
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);
yoyo837's avatar
yoyo837 committed
32 33 34
            if (redirect.startsWith('/#')) {
              redirect = redirect.substr(2);
            }
35 36 37 38 39
          } else {
            window.location.href = redirect;
            return;
          }
        }
40
        yield put(routerRedux.replace(redirect || '/'));
41
      }
ddcat1115's avatar
fix #52  
ddcat1115 committed
42
    },
43 44 45
    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
46 47 48 49 50 51 52 53 54 55
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
56 57 58
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
59
            redirect: window.location.href,
60 61
          }),
        })
62
      );
ddcat1115's avatar
fix #52  
ddcat1115 committed
63
    },
64 65 66
  },

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