功能:完善订单流程和加固
This commit is contained in:
@@ -8,6 +8,7 @@ import { ADMIN_API_BASE_URL } from '../config/api'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
||||
import { attachRequestSignature } from '@/utils/request-signature'
|
||||
import { isAdminApiAuthFreePath } from './auth-free-paths'
|
||||
|
||||
let lastErrorTime = 0
|
||||
let lastErrorMessage = ''
|
||||
@@ -38,6 +39,25 @@ const processQueue = (error: any, token: string | null = null) => {
|
||||
failedQueue = []
|
||||
}
|
||||
|
||||
const getStoredAdminAccessToken = () => {
|
||||
return localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')
|
||||
}
|
||||
|
||||
const getRequestToken = (request: any) => {
|
||||
if (request?._authToken) {
|
||||
return request._authToken as string
|
||||
}
|
||||
const authHeader = request?.headers?.Authorization || request?.headers?.authorization
|
||||
if (typeof authHeader !== 'string') {
|
||||
return null
|
||||
}
|
||||
return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null
|
||||
}
|
||||
|
||||
const isCurrentStoredAdminToken = (token: string | null) => {
|
||||
return Boolean(token && token === getStoredAdminAccessToken())
|
||||
}
|
||||
|
||||
const showError = (msg: string) => {
|
||||
const now = Date.now()
|
||||
if (now - lastErrorTime > ERROR_DEBOUNCE_TIME || msg !== lastErrorMessage) {
|
||||
@@ -48,10 +68,14 @@ const showError = (msg: string) => {
|
||||
}
|
||||
|
||||
const isAuthFreePath = (url?: string) => {
|
||||
return Boolean(url?.includes('/auth/login') || url?.includes('/auth/login-shops/') || url?.includes('/auth/refresh'))
|
||||
return isAdminApiAuthFreePath(url)
|
||||
}
|
||||
|
||||
const handleAdminTokenExpired = () => {
|
||||
const handleAdminTokenExpired = (failedToken: string | null = null) => {
|
||||
if (!isCurrentStoredAdminToken(failedToken)) {
|
||||
return
|
||||
}
|
||||
|
||||
clearAdminSessionStorage()
|
||||
|
||||
if (Date.now() - lastErrorTime > ERROR_DEBOUNCE_TIME || lastErrorMessage !== '登录已过期,请重新登录') {
|
||||
@@ -67,14 +91,12 @@ adminApi.interceptors.request.use(
|
||||
async config => {
|
||||
let token: string | null = null
|
||||
if (!isAuthFreePath(config.url)) {
|
||||
token = localStorage.getItem('adminAccessToken')
|
||||
if (!token) {
|
||||
token = sessionStorage.getItem('adminAccessToken')
|
||||
}
|
||||
token = getStoredAdminAccessToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
}
|
||||
;(config as any)._authToken = token || null
|
||||
return attachRequestSignature(config, token, {
|
||||
authFree: isAuthFreePath(config.url)
|
||||
})
|
||||
@@ -100,6 +122,12 @@ adminApi.interceptors.response.use(
|
||||
const originalRequest = error.config as any
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
const requestToken = getRequestToken(originalRequest)
|
||||
|
||||
if (!isCurrentStoredAdminToken(requestToken)) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (!originalRequest?._retry && !isAuthFreePath(originalRequest?.url)) {
|
||||
if (isRefreshing) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -138,14 +166,14 @@ adminApi.interceptors.response.use(
|
||||
return adminApi(originalRequest)
|
||||
} catch (refreshError) {
|
||||
processQueue(refreshError, null)
|
||||
handleAdminTokenExpired()
|
||||
handleAdminTokenExpired(requestToken)
|
||||
return Promise.reject(refreshError)
|
||||
} finally {
|
||||
isRefreshing = false
|
||||
}
|
||||
}
|
||||
|
||||
handleAdminTokenExpired()
|
||||
handleAdminTokenExpired(requestToken)
|
||||
} else if (error.response?.status !== 403) {
|
||||
const errorMsg = (error.response?.data as any)?.message || error.message || '请求失败'
|
||||
showError(errorMsg)
|
||||
@@ -728,14 +756,6 @@ export const adminShopApi = {
|
||||
*/
|
||||
updateShopStatus: (id: IdType, status: number) => {
|
||||
return adminApi.put<boolean>(`/shops/status/${id}`, { status })
|
||||
},
|
||||
/**
|
||||
* `deleteShop` API call. Use this method from the page script to invoke the backend endpoint tied to this feature.
|
||||
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
|
||||
* @param id: IdType caller-supplied value for `id: IdType`
|
||||
*/
|
||||
deleteShop: (id: IdType) => {
|
||||
return adminApi.delete<boolean>(`/shops/delete/${id}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
export const WEB_API_AUTH_FREE_PATHS = [
|
||||
'/user/login',
|
||||
'/user/register',
|
||||
'/user/check/',
|
||||
'/user/refresh-token',
|
||||
'/user/send-verification-code',
|
||||
'/user/phone-login',
|
||||
'/user/wechat-mini/',
|
||||
'/user/reset-password-by-phone',
|
||||
'/legal-agreement/current',
|
||||
'/api/legal-agreement/current',
|
||||
'/product/get/',
|
||||
'/product/list/',
|
||||
'/comment/list/product/',
|
||||
'/shop/get/',
|
||||
'/shop/list/public',
|
||||
'/shop/list/simple',
|
||||
'/tag/list/all',
|
||||
'/file/get-signed-url/',
|
||||
'/admin/auth/login',
|
||||
'/admin/auth/login-shops/',
|
||||
'/admin/auth/refresh'
|
||||
] as const
|
||||
|
||||
export const ADMIN_API_AUTH_FREE_PATHS = [
|
||||
'/auth/login',
|
||||
'/auth/login-shops/',
|
||||
'/auth/refresh'
|
||||
] as const
|
||||
|
||||
const normalizePathname = (url?: string) => {
|
||||
const raw = String(url || '')
|
||||
const withoutHash = raw.split('#')[0] || ''
|
||||
const withoutQuery = withoutHash.split('?')[0] || ''
|
||||
try {
|
||||
return new URL(withoutQuery, 'http://yuminail.local').pathname
|
||||
} catch {
|
||||
return withoutQuery.startsWith('/') ? withoutQuery : `/${withoutQuery}`
|
||||
}
|
||||
}
|
||||
|
||||
const matchesAuthFreePath = (url: string | undefined, path: string) => {
|
||||
const pathname = normalizePathname(url)
|
||||
if (path.endsWith('/')) {
|
||||
return pathname === path.slice(0, -1) || pathname.startsWith(path)
|
||||
}
|
||||
return pathname === path
|
||||
}
|
||||
|
||||
export const isApiAuthFreePath = (url?: string) => {
|
||||
return WEB_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path))
|
||||
}
|
||||
|
||||
export const isAdminApiAuthFreePath = (url?: string) => {
|
||||
return ADMIN_API_AUTH_FREE_PATHS.some(path => matchesAuthFreePath(url, path))
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import { API_BASE_URL } from '../config/api'
|
||||
import type { IdType } from '@/utils/id'
|
||||
import { clearAdminSessionStorage } from '@/utils/admin-session'
|
||||
import { attachRequestSignature } from '@/utils/request-signature'
|
||||
import { isApiAuthFreePath } from './auth-free-paths'
|
||||
|
||||
// 防重复提示标志
|
||||
let lastErrorTime = 0
|
||||
@@ -31,6 +32,55 @@ let failedQueue: Array<{
|
||||
reject: (reason?: any) => void
|
||||
}> = []
|
||||
|
||||
const getStoredAccessToken = (isAdmin = false) => {
|
||||
return isAdmin
|
||||
? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken'))
|
||||
: (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken'))
|
||||
}
|
||||
|
||||
const getStoredRefreshToken = (isAdmin = false) => {
|
||||
return isAdmin
|
||||
? (localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken'))
|
||||
: (localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken'))
|
||||
}
|
||||
|
||||
const getRequestToken = (request: any) => {
|
||||
if (request?._authToken) {
|
||||
return request._authToken as string
|
||||
}
|
||||
|
||||
const authHeader = request?.headers?.Authorization || request?.headers?.authorization
|
||||
if (typeof authHeader !== 'string') {
|
||||
return null
|
||||
}
|
||||
|
||||
return authHeader.startsWith('Bearer ') ? authHeader.slice('Bearer '.length) : null
|
||||
}
|
||||
|
||||
const isCurrentStoredToken = (token: string | null, isAdmin = false) => {
|
||||
return Boolean(token && token === getStoredAccessToken(isAdmin))
|
||||
}
|
||||
|
||||
const getResponseMessage = (error: AxiosError) => {
|
||||
return (error.response?.data as any)?.message || error.message || '请求失败'
|
||||
}
|
||||
|
||||
const isTokenExpiredResponse = (error: AxiosError, requestToken: string | null) => {
|
||||
const messageText = getResponseMessage(error)
|
||||
return Boolean(
|
||||
requestToken
|
||||
&& (
|
||||
messageText.includes('Token')
|
||||
|| messageText.includes('token')
|
||||
|| messageText.includes('登录态')
|
||||
|| messageText.includes('登录已过期')
|
||||
|| messageText.includes('未登录')
|
||||
|| messageText.includes('认证')
|
||||
|| messageText.includes('重新登录')
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const processQueue = (error: any, token: string | null = null) => {
|
||||
failedQueue.forEach(prom => {
|
||||
if (error) {
|
||||
@@ -53,32 +103,14 @@ const showError = (msg: string) => {
|
||||
}
|
||||
|
||||
const isAuthFreePath = (url?: string) => {
|
||||
return [
|
||||
'/user/login',
|
||||
'/user/register',
|
||||
'/user/check/',
|
||||
'/user/refresh-token',
|
||||
'/user/send-verification-code',
|
||||
'/user/phone-login',
|
||||
'/user/wechat-mini/',
|
||||
'/user/reset-password-by-phone',
|
||||
'/legal-agreement/current',
|
||||
'/api/legal-agreement/current',
|
||||
'/product/get/',
|
||||
'/product/list/',
|
||||
'/comment/list/product/',
|
||||
'/shop/get/',
|
||||
'/shop/list/public',
|
||||
'/shop/list/simple',
|
||||
'/tag/list/all',
|
||||
'/file/get-signed-url/',
|
||||
'/admin/auth/login',
|
||||
'/admin/auth/login-shops/',
|
||||
'/admin/auth/refresh'
|
||||
].some(path => String(url || '').includes(path))
|
||||
return isApiAuthFreePath(url)
|
||||
}
|
||||
|
||||
const handleTokenExpired = (isAdmin = false) => {
|
||||
const handleTokenExpired = (isAdmin = false, failedToken: string | null = null) => {
|
||||
if (!isCurrentStoredToken(failedToken, isAdmin)) {
|
||||
return
|
||||
}
|
||||
|
||||
// 清理token和用户信息
|
||||
if (isAdmin) {
|
||||
// 清理后台管理的token
|
||||
@@ -89,6 +121,7 @@ const handleTokenExpired = (isAdmin = false) => {
|
||||
localStorage.removeItem('refreshToken')
|
||||
localStorage.removeItem('userInfo')
|
||||
sessionStorage.removeItem('accessToken')
|
||||
sessionStorage.removeItem('refreshToken')
|
||||
}
|
||||
|
||||
// 显示错误提示
|
||||
@@ -124,6 +157,7 @@ api.interceptors.request.use(
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
;(config as any)._authToken = token || null
|
||||
return attachRequestSignature(config, token, {
|
||||
authFree: isAuthFreePath(config.url)
|
||||
})
|
||||
@@ -149,28 +183,23 @@ api.interceptors.response.use(
|
||||
const originalRequest = error.config as any
|
||||
|
||||
const isWhitelistedPath = (url: string) => {
|
||||
return url?.includes('/user/login') ||
|
||||
url?.includes('/user/register') ||
|
||||
url?.includes('/user/check/') ||
|
||||
url?.includes('/user/refresh-token') ||
|
||||
url?.includes('/user/send-verification-code') ||
|
||||
url?.includes('/user/phone-login') ||
|
||||
url?.includes('/legal-agreement/current') ||
|
||||
url?.includes('/product/get/') ||
|
||||
url?.includes('/product/list/') ||
|
||||
url?.includes('/comment/list/product/') ||
|
||||
url?.includes('/shop/get/') ||
|
||||
url?.includes('/shop/list/public') ||
|
||||
url?.includes('/shop/list/simple') ||
|
||||
url?.includes('/tag/list/all') ||
|
||||
url?.includes('/file/get-signed-url/') ||
|
||||
url?.includes('/admin/auth/login') ||
|
||||
url?.includes('/admin/auth/refresh')
|
||||
return isApiAuthFreePath(url)
|
||||
}
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
// 检查是否是后台管理的API请求
|
||||
const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/')
|
||||
const requestToken = getRequestToken(originalRequest)
|
||||
const isRealTokenExpired = isTokenExpiredResponse(error, requestToken)
|
||||
|
||||
if (!isRealTokenExpired) {
|
||||
showError(getResponseMessage(error))
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (!isCurrentStoredToken(requestToken, isAdminRequest)) {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
if (!originalRequest._retry && !isWhitelistedPath(originalRequest.url)) {
|
||||
if (isRefreshing) {
|
||||
@@ -179,6 +208,7 @@ api.interceptors.response.use(
|
||||
}).then(token => {
|
||||
if (token) {
|
||||
originalRequest.headers.Authorization = `Bearer ${token}`
|
||||
originalRequest._authToken = token
|
||||
}
|
||||
return api(originalRequest)
|
||||
}).catch(err => {
|
||||
@@ -192,9 +222,9 @@ api.interceptors.response.use(
|
||||
try {
|
||||
let refreshToken
|
||||
if (isAdminRequest) {
|
||||
refreshToken = localStorage.getItem('adminRefreshToken') || sessionStorage.getItem('adminRefreshToken')
|
||||
refreshToken = getStoredRefreshToken(true)
|
||||
} else {
|
||||
refreshToken = localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken')
|
||||
refreshToken = getStoredRefreshToken(false)
|
||||
}
|
||||
|
||||
if (!refreshToken) {
|
||||
@@ -217,21 +247,23 @@ api.interceptors.response.use(
|
||||
localStorage.setItem('accessToken', newToken)
|
||||
localStorage.setItem('refreshToken', newRefreshToken)
|
||||
sessionStorage.setItem('accessToken', newToken)
|
||||
sessionStorage.setItem('refreshToken', newRefreshToken)
|
||||
}
|
||||
|
||||
processQueue(null, newToken)
|
||||
|
||||
originalRequest.headers.Authorization = `Bearer ${newToken}`
|
||||
originalRequest._authToken = newToken
|
||||
return api(originalRequest)
|
||||
} catch (refreshError) {
|
||||
processQueue(refreshError, null)
|
||||
handleTokenExpired(isAdminRequest)
|
||||
handleTokenExpired(isAdminRequest, requestToken)
|
||||
return Promise.reject(refreshError)
|
||||
} finally {
|
||||
isRefreshing = false
|
||||
}
|
||||
} else {
|
||||
handleTokenExpired(isAdminRequest)
|
||||
handleTokenExpired(isAdminRequest, requestToken)
|
||||
return Promise.reject(error)
|
||||
}
|
||||
} else if (error.response?.status !== 403) { // 403权限不足不提示
|
||||
|
||||
@@ -40,6 +40,77 @@ export interface ArtistCalendarAppointment {
|
||||
durationMinutes: number
|
||||
}
|
||||
|
||||
export interface OrderArtistReviewVO {
|
||||
id: IdType
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
artistId?: IdType
|
||||
artistName?: string
|
||||
artistAvatar?: string
|
||||
userId?: IdType
|
||||
rating?: number
|
||||
content?: string
|
||||
imageFileIds?: IdType[]
|
||||
status?: number
|
||||
statusText?: string
|
||||
submitTime?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
export interface OrderArtistReviewSubmitRequest {
|
||||
rating: number
|
||||
content?: string
|
||||
imageFileIds: IdType[]
|
||||
}
|
||||
|
||||
export interface OrderArtistChangeOptionsVO {
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
currentArtistId?: IdType
|
||||
currentArtistName?: string
|
||||
artists: Array<{
|
||||
artistId: IdType
|
||||
artistName: string
|
||||
artistAvatar?: string
|
||||
userType?: number
|
||||
participateProduction?: boolean
|
||||
}>
|
||||
}
|
||||
|
||||
export interface OrderArtistChangeRequestVO {
|
||||
id: IdType
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
productId?: IdType
|
||||
productTitle?: string
|
||||
shopId?: IdType
|
||||
userId?: IdType
|
||||
originalArtistId?: IdType
|
||||
originalArtistName?: string
|
||||
requestedArtistId?: IdType
|
||||
requestedArtistName?: string
|
||||
status?: string
|
||||
statusText?: string
|
||||
reason?: string
|
||||
rejectReason?: string
|
||||
reviewerId?: IdType
|
||||
reviewTime?: string
|
||||
createTime?: string
|
||||
}
|
||||
|
||||
export interface OrderArtistChangeRequestSubmitRequest {
|
||||
orderId: IdType
|
||||
orderItemId: IdType
|
||||
requestedArtistId: IdType
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface OrderArtistChangeRejectRequest {
|
||||
rejectReason?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* orderApi groups all API calls for this page domain.
|
||||
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
|
||||
@@ -59,6 +130,40 @@ export const orderApi = {
|
||||
getOrderList: async (): Promise<any[]> => {
|
||||
return await api.get<any[]>('/order/list') as unknown as any[]
|
||||
},
|
||||
|
||||
getMyPendingReviews: async (): Promise<OrderArtistReviewVO[]> => {
|
||||
return await api.get<OrderArtistReviewVO[]>('/order/review/my-pending') as unknown as OrderArtistReviewVO[]
|
||||
},
|
||||
|
||||
getOrderReviews: async (orderId: IdType): Promise<OrderArtistReviewVO[]> => {
|
||||
return await api.get<OrderArtistReviewVO[]>(`/order/${orderId}/reviews`) as unknown as OrderArtistReviewVO[]
|
||||
},
|
||||
|
||||
submitArtistReview: async (reviewId: IdType, data: OrderArtistReviewSubmitRequest): Promise<OrderArtistReviewVO> => {
|
||||
return await api.post<OrderArtistReviewVO>(`/order/review/${reviewId}/submit`, data) as unknown as OrderArtistReviewVO
|
||||
},
|
||||
|
||||
getArtistChangeOptions: async (orderId: IdType, orderItemId: IdType): Promise<OrderArtistChangeOptionsVO> => {
|
||||
return await api.get<OrderArtistChangeOptionsVO>(`/order/${orderId}/artist-change/options`, {
|
||||
params: { orderItemId }
|
||||
}) as unknown as OrderArtistChangeOptionsVO
|
||||
},
|
||||
|
||||
requestArtistChange: async (data: OrderArtistChangeRequestSubmitRequest): Promise<OrderArtistChangeRequestVO> => {
|
||||
return await api.post<OrderArtistChangeRequestVO>('/order/artist-change/request', data) as unknown as OrderArtistChangeRequestVO
|
||||
},
|
||||
|
||||
getMyPendingArtistChangeRequests: async (): Promise<OrderArtistChangeRequestVO[]> => {
|
||||
return await api.get<OrderArtistChangeRequestVO[]>('/order/artist-change/my-pending') as unknown as OrderArtistChangeRequestVO[]
|
||||
},
|
||||
|
||||
approveArtistChange: async (requestId: IdType): Promise<OrderArtistChangeRequestVO> => {
|
||||
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/approve`) as unknown as OrderArtistChangeRequestVO
|
||||
},
|
||||
|
||||
rejectArtistChange: async (requestId: IdType, data?: OrderArtistChangeRejectRequest): Promise<OrderArtistChangeRequestVO> => {
|
||||
return await api.put<OrderArtistChangeRequestVO>(`/order/artist-change/${requestId}/reject`, data || {}) as unknown as OrderArtistChangeRequestVO
|
||||
},
|
||||
|
||||
// 获取订单详情
|
||||
/**
|
||||
|
||||
@@ -180,6 +180,9 @@ export interface SystemMessageVO {
|
||||
publisherName?: string
|
||||
targetType?: string
|
||||
targetTypeName?: string
|
||||
businessType?: string
|
||||
businessId?: IdType
|
||||
actionPath?: string
|
||||
popupEnabled?: number
|
||||
popupShown?: number
|
||||
readStatus?: number
|
||||
|
||||
Reference in New Issue
Block a user