2022-11-15 11:35:54 +08:00
|
|
|
|
import { isWithoutToken } from './help'
|
2022-11-21 09:32:31 +08:00
|
|
|
|
import { getUserInfo, signoutRedirect } from '@/utils/oidc/index.js'
|
2022-11-15 11:35:54 +08:00
|
|
|
|
|
|
|
|
|
|
export function setupInterceptor(service) {
|
|
|
|
|
|
service.interceptors.request.use(
|
|
|
|
|
|
async(config) => {
|
|
|
|
|
|
// 防止缓存,给get请求加上时间戳
|
|
|
|
|
|
if (config.method === 'get') {
|
|
|
|
|
|
config.params = { ...config.params, t: new Date().getTime() }
|
|
|
|
|
|
}
|
|
|
|
|
|
// 处理不需要token的请求
|
|
|
|
|
|
if (isWithoutToken(config)) {
|
|
|
|
|
|
return config
|
2022-11-21 09:32:31 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
const userInfo = await getUserInfo()
|
|
|
|
|
|
if (userInfo) {
|
|
|
|
|
|
const { token_type, access_token } = userInfo
|
|
|
|
|
|
// config.headers.Authorization = `${token_type} ${access_token}`
|
|
|
|
|
|
config.headers.Authorization = '70aa58b4-dda7-446d-8cbf-8e6d6ab89a02'
|
|
|
|
|
|
const { VITE_CLIENT_ID } = import.meta.env
|
|
|
|
|
|
config.headers['Client-Id'] = VITE_CLIENT_ID
|
|
|
|
|
|
return config
|
|
|
|
|
|
} else {
|
|
|
|
|
|
signoutRedirect()
|
|
|
|
|
|
return Promise.reject({ response: { status: 401, message: '未登录' }})
|
|
|
|
|
|
}
|
2022-11-15 11:35:54 +08:00
|
|
|
|
}
|
|
|
|
|
|
},
|
|
|
|
|
|
(error) => Promise.reject(error)
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
service.interceptors.response.use(
|
|
|
|
|
|
(response) => {
|
|
|
|
|
|
const { method } = response?.config
|
|
|
|
|
|
const { code } = response?.data
|
|
|
|
|
|
switch (code) {
|
|
|
|
|
|
case 0:
|
|
|
|
|
|
if (method !== 'get') {
|
|
|
|
|
|
$message.success(response.data.msg)
|
|
|
|
|
|
}
|
|
|
|
|
|
break
|
|
|
|
|
|
case -1:
|
|
|
|
|
|
$message.error(response.data.msg)
|
|
|
|
|
|
break
|
|
|
|
|
|
case 401:
|
|
|
|
|
|
// 未登录(可能是token过期或者无效了)
|
2022-11-21 09:32:31 +08:00
|
|
|
|
signoutRedirect()
|
2022-11-15 11:35:54 +08:00
|
|
|
|
break
|
|
|
|
|
|
default:
|
|
|
|
|
|
break
|
|
|
|
|
|
}
|
|
|
|
|
|
return response?.data
|
|
|
|
|
|
},
|
|
|
|
|
|
(error) => {
|
2022-11-21 09:32:31 +08:00
|
|
|
|
const { status } = error.response
|
|
|
|
|
|
if (status === 401) {
|
|
|
|
|
|
signoutRedirect()
|
|
|
|
|
|
} else if (status === 403) {
|
|
|
|
|
|
$message.error('暂无权限访问,请联系管理员')
|
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
|
}
|
2022-11-15 11:35:54 +08:00
|
|
|
|
}
|
|
|
|
|
|
)
|
|
|
|
|
|
}
|