login.js 1.99 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 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
    },
陈帅's avatar
陈帅 committed
43

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

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

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