You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.4 KiB
TypeScript
96 lines
2.4 KiB
TypeScript
import { stringify } from 'querystring';
|
|
import { history, Reducer, Effect } from 'umi';
|
|
|
|
import { fakeAccountLogin } from '@/services/login';
|
|
import { setAuthority } from '@/utils/authority';
|
|
import { getPageQuery } from '@/utils/utils';
|
|
|
|
export interface StateType {
|
|
status?: 'ok' | 'error';
|
|
type?: string;
|
|
currentAuthority?: 'user' | 'guest' | 'admin';
|
|
}
|
|
|
|
export interface LoginModelType {
|
|
namespace: string;
|
|
state: StateType;
|
|
effects: {
|
|
login: Effect;
|
|
logout: Effect;
|
|
};
|
|
reducers: {
|
|
changeLoginStatus: Reducer<StateType>;
|
|
};
|
|
}
|
|
|
|
const Model: LoginModelType = {
|
|
namespace: 'login',
|
|
|
|
state: {
|
|
status: undefined,
|
|
},
|
|
|
|
effects: {
|
|
*login({ payload }, { call, put }) {
|
|
const response = yield call(fakeAccountLogin, payload);
|
|
yield put({
|
|
type: 'changeLoginStatus',
|
|
payload: response,
|
|
});
|
|
// Login successfully
|
|
if (response.retcode === 1) {
|
|
const urlParams = new URL(window.location.href);
|
|
const params = getPageQuery();
|
|
let { redirect } = params as { redirect: string };
|
|
if (redirect) {
|
|
const redirectUrlParams = new URL(redirect);
|
|
if (redirectUrlParams.origin === urlParams.origin) {
|
|
redirect = redirect.substr(urlParams.origin.length);
|
|
if (redirect.match(/^\/.*#/)) {
|
|
redirect = redirect.substr(redirect.indexOf('#') + 1);
|
|
}
|
|
} else {
|
|
window.location.href = '/';
|
|
return;
|
|
}
|
|
}
|
|
history.replace(redirect || '/');
|
|
}
|
|
},
|
|
|
|
logout() {
|
|
const { redirect } = getPageQuery();
|
|
// Note: There may be security issues, please note
|
|
if (window.location.pathname !== '/user/login' && !redirect) {
|
|
localStorage.clear()
|
|
history.replace({
|
|
pathname: '/user/login',
|
|
search: stringify({
|
|
redirect: window.location.href,
|
|
}),
|
|
});
|
|
}
|
|
},
|
|
},
|
|
|
|
reducers: {
|
|
changeLoginStatus(state, { payload }) {
|
|
if (payload.retcode) {
|
|
let list: any[] = []
|
|
if (payload.data.user && payload.data.user.permission) {
|
|
list = JSON.parse(payload.data.user.permission)
|
|
}
|
|
setAuthority(list)
|
|
localStorage.setItem('token', payload.data.token)
|
|
}
|
|
return {
|
|
...state,
|
|
status: payload.retcode?'ok':'error',
|
|
type: payload.type,
|
|
};
|
|
},
|
|
},
|
|
};
|
|
|
|
export default Model;
|