Files

524 lines
18 KiB
JavaScript

/**
* Purpose: auth supports request.js by holding or executing the auth page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const auth = require('./auth')
/**
* Purpose: actionGuard supports request.js by holding or executing the action guard page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const actionGuard = require('./action-guard')
/**
* Purpose: idleSession supports request.js by holding or executing the idle session page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const idleSession = require('./idle-session')
const { API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
/**
* Purpose: HEADER_TIMESTAMP supports request.js by holding or executing the header timestamp page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_TIMESTAMP = 'X-Timestamp'
/**
* Purpose: HEADER_NONCE supports request.js by holding or executing the header nonce page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_NONCE = 'X-Nonce'
/**
* Purpose: HEADER_SIGNATURE supports request.js by holding or executing the header signature page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_SIGNATURE = 'X-Signature'
/**
* Purpose: HEADER_SIGNATURE_VERSION supports request.js by holding or executing the header signature version page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
/**
* Purpose: DEVICE_ID_HEADER supports request.js by holding or executing the device id header page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEVICE_ID_HEADER = 'X-Device-Id'
/**
* Purpose: isRefreshing supports request.js by holding or executing the is refreshing page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let isRefreshing = false
/**
* Purpose: requestQueue supports request.js by holding or executing the request queue page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let requestQueue = []
/**
* Purpose: redirectingToAuth supports request.js by holding or executing the redirecting to auth page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let redirectingToAuth = false
/**
* Purpose: inflightRequests supports request.js by holding or executing the inflight requests page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const inflightRequests = {}
/**
* Purpose: buildRequestUrl supports request.js by holding or executing the build request url page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildRequestUrl(url, params) {
const query = Object.keys(params || {})
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&')
const target = `${API_BASE_URL}${url}`
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
}
/**
* Purpose: isWhitelistedPath supports request.js by holding or executing the is whitelisted path page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isWhitelistedPath(url) {
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',
'/product/get/',
'/product/list/',
'/comment/list/product/',
'/nail-artist/profile/',
'/nail-artist/',
'/shop/get/',
'/shop/trust-profile/',
'/shop/list/public',
'/shop/list/simple',
'/tag/list/all',
'/tag/list/filter-options',
'/file/get-signed-url/'
].some(path => String(url || '').includes(path))
}
/**
* Purpose: normalizeError supports request.js by holding or executing the normalize error page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function normalizeError(message, statusCode, raw) {
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
error.statusCode = statusCode
error.raw = raw
return error
}
/**
* Purpose: rawRequest supports request.js by holding or executing the raw request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function rawRequest(options) {
idleSession.markActive()
return new Promise((resolve, reject) => {
wx.request({
...options,
success: resolve,
fail: reject
})
})
}
/**
* Purpose: queueRequest supports request.js by holding or executing the queue request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function queueRequest(retry) {
return new Promise((resolve, reject) => {
requestQueue.push({
resolve,
reject,
retry
})
})
}
/**
* Purpose: flushQueue supports request.js by holding or executing the flush queue page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function flushQueue(error) {
const queue = requestQueue.slice()
requestQueue = []
queue.forEach(item => {
if (error) {
item.reject(error)
return
}
item.retry().then(item.resolve).catch(item.reject)
})
}
/**
* Purpose: redirectToAuth supports request.js by holding or executing the redirect to auth page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function redirectToAuth() {
if (redirectingToAuth) {
return
}
redirectingToAuth = true
const pages = getCurrentPages()
const current = pages[pages.length - 1]
const currentPath = current ? `/${current.route}` : '/pages/home/index'
const currentQuery = current && current.options ? current.options : {}
const queryString = Object.keys(currentQuery)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(currentQuery[key])}`)
.join('&')
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
wx.showToast({
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
icon: 'none'
})
setTimeout(() => {
wx.reLaunch({
url: `/pages/auth/index?redirect=${encodeURIComponent(redirect)}`,
complete() {
redirectingToAuth = false
}
})
}, 300)
}
/**
* Purpose: buildSignatureHeaders supports request.js by holding or executing the build signature headers page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildSignatureHeaders(options) {
const headers = {
[DEVICE_ID_HEADER]: getDeviceId()
}
const method = String(options.method || 'GET').toUpperCase()
const accessToken = auth.getAccessToken()
if (accessToken && !isWhitelistedPath(options.url)) {
headers.Authorization = `Bearer ${accessToken}`
}
if (!ENABLE_REQUEST_SIGNING || !accessToken || isWhitelistedPath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) {
return headers
}
const formData = options.formData
const hasFormData = formData && Object.keys(formData).length > 0
const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase()
const payload = contentType.includes('application/json') && !hasFormData
? buildJsonPayload(options.data)
: buildCanonicalParams(formData || options.data || options.params)
const timestamp = String(Date.now())
const nonce = randomNonce()
const canonical = [
method,
options.url,
timestamp,
nonce,
sha256Hex(payload)
].join('\n')
headers[HEADER_TIMESTAMP] = timestamp
headers[HEADER_NONCE] = nonce
headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical)
headers[HEADER_SIGNATURE_VERSION] = 'v1'
return headers
}
/**
* Purpose: refreshToken supports request.js by holding or executing the refresh token page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function refreshToken() {
const refreshTokenValue = auth.getRefreshToken()
if (!refreshTokenValue) {
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
}
const response = await rawRequest({
url: `${API_BASE_URL}/user/refresh-token`,
method: 'POST',
timeout: REQUEST_TIMEOUT,
header: {
'Content-Type': 'application/json',
[DEVICE_ID_HEADER]: getDeviceId()
},
data: {
refreshToken: refreshTokenValue
}
})
if (response.statusCode === 200 && response.data && response.data.code === 200 && response.data.data) {
auth.setSession(response.data.data)
const app = getApp()
if (app && typeof app.bootstrapSession === 'function') {
app.bootstrapSession()
}
return response.data.data
}
throw normalizeError(
(response.data && response.data.message) || '\u5237\u65b0\u767b\u5f55\u6001\u5931\u8d25',
response.statusCode,
response
)
}
/**
* Purpose: handleUnauthorized supports request.js by holding or executing the handle unauthorized page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function handleUnauthorized(options) {
if (isWhitelistedPath(options.url)) {
throw normalizeError('\u8bf7\u6c42\u9700\u8981\u767b\u5f55\uff0c\u4f46\u5f53\u524d\u9875\u9762\u5141\u8bb8\u533f\u540d\u67e5\u770b', 401)
}
if (options._retry) {
auth.clearSession()
const app = getApp()
if (app && typeof app.clearUserSession === 'function') {
app.clearUserSession()
}
redirectToAuth()
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
}
if (isRefreshing) {
return queueRequest(() => request({
...options,
_retry: true
}))
}
isRefreshing = true
try {
await refreshToken()
flushQueue(null)
return await request({
...options,
_retry: true
})
} catch (error) {
flushQueue(error)
auth.clearSession()
const app = getApp()
if (app && typeof app.clearUserSession === 'function') {
app.clearUserSession()
}
redirectToAuth()
throw error
} finally {
isRefreshing = false
}
}
/**
* Purpose: unwrapResponse supports request.js by holding or executing the unwrap response page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function unwrapResponse(res, options) {
idleSession.markActive()
if (res.statusCode === 401) {
return handleUnauthorized(options)
}
if (res.statusCode >= 400) {
throw normalizeError(
(res.data && res.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
res.statusCode,
res
)
}
const payload = res.data
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
if (payload.code === 200) {
return payload.data
}
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
}
return payload
}
/**
* Purpose: buildDedupeKey supports request.js by holding or executing the build dedupe key page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildDedupeKey(options, method) {
if (options.skipDedupe) {
return ''
}
if (options.dedupeKey) {
return `${method}:${options.dedupeKey}`
}
if (method === 'GET') {
return `${method}:${options.url}:${buildCanonicalParams(options.params)}`
}
return ''
}
/**
* Purpose: isSafeMethod supports request.js by holding or executing the is safe method page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isSafeMethod(method) {
return ['GET', 'HEAD', 'OPTIONS'].includes(method)
}
/**
* Purpose: buildActionFingerprint supports request.js by holding or executing the build action fingerprint page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildActionFingerprint(options, method) {
const paramsText = buildCanonicalParams(options.params)
const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data)
return sha256Hex([
options.url || '',
paramsText,
payloadText
].join('\n'))
}
/**
* Purpose: resolveRepeatMessage supports request.js by holding or executing the resolve repeat message page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resolveRepeatMessage(url) {
const path = String(url || '')
if (
path.includes('/user/login')
|| path.includes('/user/phone-login')
|| path.includes('/user/register')
|| path.includes('/user/reset-password-by-phone')
|| path.includes('/user/wechat-mini/')
) {
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/send-verification-code')) {
return '\u9a8c\u8bc1\u7801\u53d1\u9001\u5904\u7406\u4e2d\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5'
}
if (path.includes('/switch-shop')) {
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/order/create')) {
return '\u8ba2\u5355\u6b63\u5728\u63d0\u4ea4\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
if (path.includes('/upload')) {
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/logout')) {
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/cart/')) {
return '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
/**
* Purpose: buildActionGuardConfig supports request.js by holding or executing the build action guard config page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildActionGuardConfig(options, method) {
if (options.skipActionGuard || isSafeMethod(method)) {
return null
}
return {
scope: options.guardScope,
key: options.actionKey || `${method}:${options.url}:${buildActionFingerprint(options, method)}`,
message: options.repeatMessage || resolveRepeatMessage(options.url)
}
}
/**
* Purpose: request supports request.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function request(options) {
const method = String(options.method || 'GET').toUpperCase()
const dedupeKey = buildDedupeKey(options, method)
if (dedupeKey && inflightRequests[dedupeKey]) {
return inflightRequests[dedupeKey]
}
const signatureHeaders = buildSignatureHeaders({
url: options.url,
method,
data: options.data,
params: options.params,
header: options.header
})
const header = {
'Content-Type': 'application/json',
...signatureHeaders,
...(options.header || {})
}
const requestOptions = {
...options,
method,
header
}
const actionGuardConfig = buildActionGuardConfig(options, method)
const executeRequest = () => new Promise((resolve, reject) => {
wx.request({
url: buildRequestUrl(options.url, method === 'GET' ? options.params : undefined),
method,
timeout: options.timeout || REQUEST_TIMEOUT,
header,
data: method === 'GET' ? undefined : options.data,
success: async res => {
try {
const data = await unwrapResponse(res, requestOptions)
resolve(data)
} catch (error) {
reject(error)
}
},
fail: error => {
reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error))
}
})
})
const task = (actionGuardConfig
? actionGuard.run(actionGuardConfig.scope, actionGuardConfig.key, executeRequest, {
message: actionGuardConfig.message
})
: executeRequest()
).finally(() => {
if (dedupeKey) {
delete inflightRequests[dedupeKey]
}
})
if (dedupeKey) {
inflightRequests[dedupeKey] = task
}
return task
}
request.buildSignatureHeaders = buildSignatureHeaders
request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER
module.exports = request