login.js 1.93 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 6 7 8 9 10 11 12 13

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
afc163's avatar
afc163 committed
14
    *login({ payload }, { call, put }) {
ddcat1115's avatar
ddcat1115 committed
15
      const response = yield call(fakeAccountLogin, payload);
16
      yield put({
17
        type: 'changeLoginStatus',
18 19
        payload: response,
      });
afc163's avatar
afc163 committed
20 21
      // Login successfully
      if (response.status === 'ok') {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
22
        reloadAuthorized();
23 24 25 26 27 28 29 30 31 32 33 34
        const urlParams = new URL(window.location.href);
        let redirect = urlParams.searchParams.get('redirect');
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.push(redirect || '/'));
afc163's avatar
afc163 committed
35
      }
36
    },
37 38 39 40 41 42 43
    *logout(_, { put, select }) {
      try {
        // get location pathname
        const urlParams = new URL(window.location.href);
        const pathname = yield select(state => state.routing.location.pathname);
        // add the parameters in the url
        urlParams.searchParams.set('redirect', pathname);
jim's avatar
jim committed
44
        window.history.replaceState(null, 'login', urlParams.href);
45 46 47 48 49 50 51 52
      } finally {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currentAuthority: 'guest',
          },
        });
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
53 54
        reloadAuthorized();
        yield put(routerRedux.push('/user/login'));
55
      }
ddcat1115's avatar
fix #52  
ddcat1115 committed
56
    },
57 58 59
  },

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