免登录处理

This commit is contained in:
李志强 2023-12-29 11:19:20 +08:00
parent c7a389af19
commit c403dadb93
2 changed files with 64 additions and 54 deletions

View File

@ -15,6 +15,9 @@ import defaultSettings from '../config/defaultSettings';
import iconStyle from '../public/樽海鞘_图案.svg';
import './modelstyle.css';
import { getRoutersInfo, getUserInfo } from './services/session';
import { login } from './services/login';
import { setSessionToken } from './access';
import { Route } from 'react-router';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
@ -23,6 +26,46 @@ export const initialStateConfig = {
loading: <PageLoading />,
};
const fetchUserInfo = async (setInitialState: any) => {
try {
const resp = await getUserInfo()
if (resp === undefined || resp.code !== 200) {
const response = await login({ username: 'admin', password: 'admin123' });
const current = new Date();
const expireTime = current.setTime(current.getTime() + 1000 * 12 * 60 * 60);
setSessionToken(response.token, response.token, expireTime);
const { user, permissions } = await getUserInfo()
await setInitialState((s) => ({
...s,
currentUser: { permissions, user },
}));
let menus = await getRoutersInfo();
if (window.localStorage.getItem('redirectPath')?.indexOf('?') !== -1) {
menus = menus.map((item) => {
return {
...item,
hideInMenu: true,
};
});
}
setInitialState((preInitialState: any) => ({
...preInitialState,
menus,
})).then(() => {
const path = window.localStorage.getItem("redirectPath") || loginPath
history.push(path)
})
} else {
return { ...resp.user, permissions: resp.permissions } as API.CurrentUser
}
} catch (error) {
console.log(error);
history.push(loginPath)
}
return undefined
}
/**
* @see https://umijs.org/zh-CN/plugins/plugin-initial-state
* */
@ -30,45 +73,9 @@ export async function getInitialState(): Promise<{
settings?: Partial<LayoutSettings>;
currentUser?: API.CurrentUser;
loading?: boolean;
fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
fetchUserInfo?: (params: any) => Promise<API.CurrentUser | undefined>;
}> {
const fetchUserInfo = async () => {
try {
const resp = await getUserInfo();
if (resp === undefined || resp.code !== 200) {
history.push(loginPath);
// const response = await login({
// username: 'admin',
// password: 'admin123',
// });
// if (response.code === 200) {
// const current = new Date();
// const expireTime = current.setTime(current.getTime() + 1000 * 12 * 60 * 60);
// setSessionToken(response.token, response.token, expireTime);
// fetchUserInfo()
// }
} else {
return { ...resp.user, permissions: resp.permissions } as API.CurrentUser;
}
} catch (error) {
console.log(error);
history.push(loginPath);
}
return undefined;
};
// 如果是登录页面,不执行
if (history.location.pathname !== loginPath) {
console.log('chufal');
const currentUser = await fetchUserInfo();
return {
settings: defaultSettings,
currentUser,
fetchUserInfo,
};
}
return {
fetchUserInfo,
settings: defaultSettings,
@ -83,24 +90,22 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) =
content: initialState?.currentUser?.userName,
},
// footerRender: () => <Footer />,
onPageChange: () => {
const { location } = history;
// 如果没有登录,重定向到 login
if (!initialState?.currentUser && location.pathname !== loginPath) {
history.push(loginPath);
onPageChange: async () => {
if (!initialState?.currentUser?.userId) {
fetchUserInfo?.(setInitialState);
}
},
links: isDev
? [
<Link key="openapi" to="/umi/plugin/openapi" target="_blank">
<LinkOutlined />
<span>OpenAPI </span>
</Link>,
<Link key="docs" to="/~docs">
<BookOutlined />
<span></span>
</Link>,
]
<Link key="openapi" to="/umi/plugin/openapi" target="_blank">
<LinkOutlined />
<span>OpenAPI </span>
</Link>,
<Link key="docs" to="/~docs">
<BookOutlined />
<span></span>
</Link>,
]
: [],
menuHeaderRender: false,
menu: {
@ -110,6 +115,11 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) =
},
request: async () => {
if (!initialState?.currentUser?.userId) {
let path = window.location.pathname
if (window.location.search) {
path += '?hideInMenu=true'
}
window.localStorage.setItem("redirectPath", path)
return [];
}
// initialState.currentUser 中包含了所有用户信息

View File

@ -84,7 +84,7 @@ const Login: React.FC = () => {
// 如果失败去设置用户错误信息
setUserLoginState({status: 'error', type: 'account', massage: response.msg});
message.error(response.msg);
getCaptchaCode();
// getCaptchaCode();
}
} catch (error) {
clearSessionToken();
@ -93,13 +93,13 @@ const Login: React.FC = () => {
defaultMessage: '登录失败,请重试!',
});
message.error(defaultLoginFailureMessage);
getCaptchaCode();
// getCaptchaCode();
}
};
const { status, type: loginType, massage } = userLoginState;
useEffect(() => {
getCaptchaCode();
// getCaptchaCode();
}, []);
return (