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

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
afc163's avatar
afc163 committed
15
    *login({ payload }, { call, put }) {
ddcat1115's avatar
ddcat1115 committed
16
      const response = yield call(fakeAccountLogin, payload);
17
      yield put({
18
        type: 'changeLoginStatus',
19 20
        payload: response,
      });
afc163's avatar
afc163 committed
21 22
      // Login successfully
      if (response.status === 'ok') {
陈帅's avatar
陈帅 committed
23
        reloadAuthorized();
24
        const urlParams = new URL(window.location.href);
yoyo837's avatar
yoyo837 committed
25 26
        const params = getPageQuery();
        let { redirect } = params;
27 28 29 30
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
yoyo837's avatar
yoyo837 committed
31 32 33
            if (redirect.startsWith('/#')) {
              redirect = redirect.substr(2);
            }
34 35 36 37 38
          } else {
            window.location.href = redirect;
            return;
          }
        }
39
        yield put(routerRedux.replace(redirect || '/'));
afc163's avatar
afc163 committed
40
      }
41
    },
42 43 44 45 46 47 48 49 50 51
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
52 53 54 55 56
        routerRedux.push(
          getQueryPath('/user/login', {
            redirect: window.location.href,
          })
        )
57
      );
ddcat1115's avatar
fix #52  
ddcat1115 committed
58
    },
59 60 61
  },

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