Commit df3e7736 authored by 前端-许佳敏's avatar 前端-许佳敏

加入权限

parent 7d27ce17
......@@ -10,7 +10,7 @@ import proxy from './proxy'
import theme from './theme.config'
export default defineConfig({
title: 'God-Template',
title: '瓴犀平台后台',
locale: {
antd: true,
// 默认情况下,当前语言环境的识别按照:localStorage 中 umi_locale 值 > 浏览器检测 > default 设置的默认语言 > 中文
......
......@@ -8,6 +8,8 @@ import '@/global/styles/global.less'; // 导入全局样式
// 默认引入所有的ant样式, 不引入css因为无法做到变量覆盖
import 'antd/dist/antd.less';
import { setup } from '@formily/antd-components';
import { getAuth, setAuth, setRouters } from './utils/auth';
import { PublicApi } from './services/api';
setup();
let extraRoutes: never[] = [];
......@@ -36,21 +38,22 @@ let extraRoutes: never[] = [];
* @date 2020-05-20
* @export
*/
// export function render(oldRender:Function) {
// // 做动态路由
// fetch('/api').then((res: any) => {
// extraRoutes = res.routes
// })
export function render(oldRender:Function) {
const authInfo = getAuth()
if (authInfo) {
PublicApi.getMemberManageLoginReget().then(res => {
const { data } = res
setAuth({
memberId: data.memberId,
userId: data.userId,
token: data.token
})
setRouters(data.urls)
})
}
// // 做权限校验
// fetch('/auth').then((res: any) => {
// if (res.isLogin) {
// oldRender()
// } else {
// history.push('/login')
// }
// })
// }
oldRender()
}
/**
* @description 在初始加载和路由切换时做一些事情
......
......@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>God-Template</title>
<title>瓴犀平台后台</title>
</head>
<body>
<div id="root"></div>
......
......@@ -5,6 +5,8 @@ import { UserOutlined, LockOutlined, CloudFilled, SafetyOutlined } from '@ant-de
import request from '@/utils/request';
import './style.less';
import logo from '@/asserts/logo_w.png'
import { PublicApi } from '@/services/api';
import { setAuth, setRouters } from '@/utils/auth';
// import leftImg from '@/asserts/image_ad.png'
interface IndexState {
......@@ -77,12 +79,15 @@ class Index extends Component<{}, IndexState> {
onFinish = (values:any) => {
console.log('Received values of form: ', values);
fakeAccountLogin(values).then(res => {
if(res.code === 200){
history.push('/')
message.success('登录成功!')
}
console.log(res, 'res')
PublicApi.postMemberManageLogin(values).then(res => {
const { data } = res
setAuth({
memberId: data.memberId,
userId: data.userId,
token: data.token
})
setRouters(data.urls)
history.push('/')
}).catch(error => {
console.error(error)
});
......@@ -116,7 +121,7 @@ class Index extends Component<{}, IndexState> {
onFinish={this.onFinish}
>
<Form.Item
name="username"
name="account"
rules={[{ required: true, message: '请输入用户名!' }]}
>
<Input
......
import { isDev } from '@/constants'
export interface AuthInfo {
userId: number,
memberId: number,
token: string
}
export const setAuth = (info: AuthInfo) => {
window.localStorage.setItem('auth', JSON.stringify(info))
}
export const getAuth = () => {
try {
return JSON.parse(window.localStorage.getItem('auth')) || null
} catch (error) {
return {}
}
}
export const setRouters = (routers: any[]) => {
window.sessionStorage.setItem('rt', JSON.stringify(routers))
}
export const getRouters = () => {
try {
return JSON.parse(window.sessionStorage.getItem('rt')).concat([
'/memberCenter/commodityAbility',
'/memberCenter/commodityAbility/classAndProperty',
'/memberCenter/commodityAbility/classAndProperty/attribute'
]) || []
} catch (error) {
return []
}
}
export const removeRouters = () => {
window.sessionStorage.removeItem('rt')
}
export const removeAuth = () => {
window.localStorage.removeItem('auth')
}
export const asyncRouter = async (routeLists: string[], routes: any[]) => {
for (let i = 0; i < routes.length; i++) {
const item = routes[i]
if (item.routes) {
asyncRouter(routeLists, item.routes)
} else {
// 参与权限校验的页面
if (item.path && !routeLists.includes(item.path)) {
item.hideInMenu = true
item.noAuth = true
}
}
}
}
\ No newline at end of file
import { extend, ResponseError, OnionOptions, RequestOptionsInit, ResponseInterceptor, OnionMiddleware, Context, RequestMethod } from 'umi-request';
import responseCode from '@/constants/responseCode'
import { IRequestError, IRequestSuccess } from '..';
import { history } from 'umi'
import { message } from 'antd'
import { getAuth, removeAuth } from './auth';
export type CtlType = 'none' | 'message'
// 根前缀请求路径
......@@ -17,7 +19,10 @@ export interface IApiRequest extends RequestOptionsInit {
* umi-request文档 https://github.com/umijs/umi-request/blob/master/README_zh-CN.md
*
*/
const errorMessage = {
type httpStatus = {
[key: number]: string
}
const errorMessage: httpStatus = {
400: "发出的请求有错误,服务器没有进行新建或修改数据的操作。",
401: "用户没有权限(令牌、用户名、密码错误)。",
403: "用户得到授权,但是访问是被禁止的。",
......@@ -28,7 +33,7 @@ const errorMessage = {
500: "服务器发生错误,请检查服务器。",
502: "网关错误。",
503: "服务不可用,服务器暂时过载或维护。",
504: "网关超时。"
504: "网关超时。",
};
const errorHandler = (error: ResponseError): IRequestError => {
......@@ -47,7 +52,6 @@ const errorHandler = (error: ResponseError): IRequestError => {
const defaultHeaders = {
'Content-Type': 'Application/json',
'token': 'lingxineverexpireadmintoken',
'source': '99'
}
......@@ -58,17 +62,25 @@ const baseRequest = extend({
timeout: 30 * 1000,
headers: defaultHeaders,
credentials: 'include', // 默认请求是否带上cookie
errorHandler,
prefix: '/api'
// errorHandler
});
// 请求拦截器
baseRequest.interceptors.request.use((url: string, options: RequestOptionsInit): { url: string, options: RequestOptionsInit } => {
// 判断是否有权限
const loginAfterHeaders = getAuth()
const headers = {
...options.headers,
...loginAfterHeaders
}
return {
// 前缀如果已经带上api, 跳过自动补前缀
// url: url.startsWith('/api') ? url : basePrefix + url,
url,
options,
url: url.startsWith('/api') ? url : basePrefix + url,
options: {
...options,
headers
},
};
});
......@@ -90,10 +102,26 @@ class ApiRequest {
createRequest<T>(url: string, options: IApiRequest = { ctlType: 'none' }): Promise<IRequestSuccess<T>> {
return new Promise((resolve, reject) => {
baseRequest<IRequestSuccess<T>>(url, options).then(res => {
// 登录验证
if (res.code === 1101) {
removeAuth()
history.replace('/user/login')
message.error(res.message)
return false
}
if (res.code === 1000) {
options.ctlType === 'message' && message.success(res.message)
resolve(res)
} else {
// 未登录
if (res.code === 1101) {
history.push('/user/login')
reject()
}
message.error(res.message)
}
resolve(res)
}).catch((err: IRequestError) => {
// http错误处理, 直接透传
reject(err)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment