login.js 1.86 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import { routerRedux } from 'dva/router';
2
import { stringify } from 'qs';
afc163's avatar
afc163 committed
3
import { fakeAccountLogin } from '../services/api';
ddcat1115's avatar
ddcat1115 committed
4
import { setAuthority } from '../utils/authority';
陈帅's avatar
陈帅 committed
5
import { reloadAuthorized } from '../utils/Authorized';
6
import { getPageQuery } from '../utils/utils';
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 || '/'));
afc163's avatar
afc163 committed
41
      }
42
    },
43 44 45 46 47 48 49 50 51 52
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
53 54 55
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
56
            redirect: window.location.href,
57 58
          }),
        })
59
      );
ddcat1115's avatar
fix #52  
ddcat1115 committed
60
    },
61 62 63
  },

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