修复小程序令牌过期登录循环
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
const assert = require('assert')
|
||||
const auth = require('./utils/auth')
|
||||
|
||||
const LOGIN_PREFERENCE_KEY = 'jayucloud_salon_login_preference'
|
||||
const storage = {}
|
||||
@@ -96,7 +97,18 @@ async function run() {
|
||||
appDefinition.logoutDevice()
|
||||
assert.strictEqual(storage[LOGIN_PREFERENCE_KEY], undefined)
|
||||
assert.strictEqual(appDefinition.globalData.userInfo, null)
|
||||
assert.strictEqual(appDefinition.globalData.wechatLoginState, null)
|
||||
assert.strictEqual(appDefinition.globalData.reviewNoticeShown, false)
|
||||
|
||||
appDefinition.globalData.wechatLoginState = { status: 'SUCCESS', accessToken: 'expired-token' }
|
||||
appDefinition.clearSession()
|
||||
assert.strictEqual(appDefinition.globalData.wechatLoginState, null)
|
||||
|
||||
assert.strictEqual(auth.beginSessionExpiredHandling(), true)
|
||||
appDefinition.setSession({ accessToken: 'profile-update-token' })
|
||||
assert.strictEqual(auth.beginSessionExpiredHandling(), false)
|
||||
appDefinition.setSession({ accessToken: 'new-login-token' }, true)
|
||||
assert.strictEqual(auth.beginSessionExpiredHandling(), true)
|
||||
}
|
||||
|
||||
run().catch(error => {
|
||||
|
||||
@@ -113,7 +113,7 @@ App({
|
||||
this.globalData.reviewNoticeShown = false
|
||||
this.globalData.openEmployeeReview = false
|
||||
}
|
||||
auth.setSession(session)
|
||||
auth.setSession(session, newLoginSession)
|
||||
this.bootstrapSession()
|
||||
},
|
||||
|
||||
@@ -121,6 +121,7 @@ App({
|
||||
auth.clearSession()
|
||||
profileCache.invalidate()
|
||||
this.globalData.userInfo = null
|
||||
this.globalData.wechatLoginState = null
|
||||
this.globalData.reviewNoticeShown = false
|
||||
this.globalData.openEmployeeReview = false
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ const SESSION_KEY = 'jayucloud-salon_session'
|
||||
const LOGIN_PREFERENCE_KEY = 'jayucloud_salon_login_preference'
|
||||
const PHONE_BANNER_DISMISSED_KEY = 'jayucloud_salon_phone_banner_dismissed'
|
||||
const PROFILE_PROMPT_SKIPPED_KEY = 'jayucloud_salon_profile_prompt_skipped'
|
||||
let sessionExpiredHandling = false
|
||||
|
||||
function getSession() {
|
||||
try {
|
||||
@@ -11,14 +12,25 @@ function getSession() {
|
||||
}
|
||||
}
|
||||
|
||||
function setSession(session) {
|
||||
function setSession(session, newLoginSession = false) {
|
||||
wx.setStorageSync(SESSION_KEY, session || {})
|
||||
if (newLoginSession) {
|
||||
sessionExpiredHandling = false
|
||||
}
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
wx.removeStorageSync(SESSION_KEY)
|
||||
}
|
||||
|
||||
function beginSessionExpiredHandling() {
|
||||
if (sessionExpiredHandling) {
|
||||
return false
|
||||
}
|
||||
sessionExpiredHandling = true
|
||||
return true
|
||||
}
|
||||
|
||||
function getAccessToken() {
|
||||
const session = getSession()
|
||||
return session.accessToken || session.token || ''
|
||||
@@ -47,6 +59,7 @@ module.exports = {
|
||||
getSession,
|
||||
setSession,
|
||||
clearSession,
|
||||
beginSessionExpiredHandling,
|
||||
getAccessToken,
|
||||
getLoginPreference,
|
||||
setLoginPreference,
|
||||
|
||||
@@ -7,8 +7,6 @@ const HEADER_NONCE = 'X-Nonce'
|
||||
const HEADER_SIGNATURE = 'X-Signature'
|
||||
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
|
||||
|
||||
let sessionExpiredHandling = false
|
||||
|
||||
function buildUrl(url, params) {
|
||||
const sourceParams = params || {}
|
||||
const baseUrl = sourceParams.__baseUrl ? sourceParams.__baseUrl : API_DOMAIN
|
||||
@@ -42,10 +40,9 @@ function clearRuntimeSession() {
|
||||
}
|
||||
|
||||
function redirectToLoginAfterExpired(message) {
|
||||
if (sessionExpiredHandling) {
|
||||
if (!auth.beginSessionExpiredHandling()) {
|
||||
return
|
||||
}
|
||||
sessionExpiredHandling = true
|
||||
clearRuntimeSession()
|
||||
wx.showToast({
|
||||
title: message,
|
||||
@@ -54,16 +51,16 @@ function redirectToLoginAfterExpired(message) {
|
||||
})
|
||||
setTimeout(() => {
|
||||
wx.reLaunch({
|
||||
url: '/pages/login/index',
|
||||
complete() {
|
||||
sessionExpiredHandling = false
|
||||
}
|
||||
url: '/pages/login/index'
|
||||
})
|
||||
}, 700)
|
||||
}
|
||||
|
||||
function handleUnauthorized(response) {
|
||||
function handleUnauthorized(response, url) {
|
||||
const message = resolveResponseMessage(response, '登录已过期,请重新登录')
|
||||
if (isAuthFreePath(url)) {
|
||||
return normalizeError(message, response)
|
||||
}
|
||||
redirectToLoginAfterExpired(message)
|
||||
return normalizeError(message, response)
|
||||
}
|
||||
@@ -163,7 +160,7 @@ function request(options) {
|
||||
},
|
||||
success(response) {
|
||||
if (response.statusCode === 401) {
|
||||
reject(handleUnauthorized(response))
|
||||
reject(handleUnauthorized(response, options.url))
|
||||
return
|
||||
}
|
||||
if (response.statusCode >= 400) {
|
||||
@@ -176,8 +173,8 @@ function request(options) {
|
||||
resolve(payload.data)
|
||||
return
|
||||
}
|
||||
if (payload.code === 401) {
|
||||
reject(handleUnauthorized({ data: payload }))
|
||||
if (Number(payload.code) === 401) {
|
||||
reject(handleUnauthorized({ data: payload }, options.url))
|
||||
return
|
||||
}
|
||||
reject(normalizeError(payload.message || '请求失败', payload))
|
||||
@@ -194,5 +191,6 @@ function request(options) {
|
||||
|
||||
request.buildSignatureHeaders = buildSignatureHeaders
|
||||
request.toBackendRequestPath = toBackendRequestPath
|
||||
request.handleUnauthorized = handleUnauthorized
|
||||
|
||||
module.exports = request
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
const assert = require('assert')
|
||||
|
||||
const storage = {}
|
||||
const requests = []
|
||||
const navigations = []
|
||||
const scheduled = []
|
||||
let clearedSessions = 0
|
||||
let globalData = { wechatLoginState: { status: 'SUCCESS', accessToken: 'expired-token' } }
|
||||
|
||||
global.wx = {
|
||||
getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }),
|
||||
getDeviceInfo: () => ({ platform: 'devtools' }),
|
||||
getStorageSync: key => storage[key],
|
||||
setStorageSync: (key, value) => { storage[key] = value },
|
||||
removeStorageSync: key => { delete storage[key] },
|
||||
request: options => requests.push(options),
|
||||
showToast: () => {},
|
||||
reLaunch: options => navigations.push(options.url)
|
||||
}
|
||||
global.getApp = () => ({
|
||||
globalData,
|
||||
clearSession() {
|
||||
clearedSessions += 1
|
||||
delete storage['jayucloud-salon_session']
|
||||
globalData.wechatLoginState = null
|
||||
}
|
||||
})
|
||||
global.setTimeout = callback => {
|
||||
scheduled.push(callback)
|
||||
return scheduled.length
|
||||
}
|
||||
|
||||
const auth = require('./auth')
|
||||
const request = require('./request')
|
||||
|
||||
async function rejectWithUnauthorized(options) {
|
||||
const pending = request(options).then(
|
||||
() => { throw new Error('Expected request to reject') },
|
||||
error => error
|
||||
)
|
||||
requests[requests.length - 1].success({
|
||||
statusCode: 401,
|
||||
data: { message: '登录已过期,请重新登录' }
|
||||
})
|
||||
return pending
|
||||
}
|
||||
|
||||
async function run() {
|
||||
auth.setSession({ accessToken: 'expired-token' }, true)
|
||||
|
||||
await rejectWithUnauthorized({ url: '/user/wechat-mini/quick-login' })
|
||||
assert.strictEqual(clearedSessions, 0)
|
||||
assert.deepStrictEqual(navigations, [])
|
||||
|
||||
await rejectWithUnauthorized({ url: '/manager/calendar' })
|
||||
assert.strictEqual(clearedSessions, 1)
|
||||
assert.strictEqual(globalData.wechatLoginState, null)
|
||||
assert.strictEqual(scheduled.length, 1)
|
||||
scheduled.shift()()
|
||||
assert.deepStrictEqual(navigations, ['/pages/login/index'])
|
||||
|
||||
await rejectWithUnauthorized({ url: '/manager/customers' })
|
||||
assert.strictEqual(clearedSessions, 1)
|
||||
assert.deepStrictEqual(navigations, ['/pages/login/index'])
|
||||
|
||||
auth.setSession({ accessToken: 'new-login-token' }, true)
|
||||
await rejectWithUnauthorized({ url: '/manager/calendar' })
|
||||
assert.strictEqual(clearedSessions, 2)
|
||||
assert.strictEqual(scheduled.length, 1)
|
||||
scheduled.shift()()
|
||||
assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index'])
|
||||
}
|
||||
|
||||
run().catch(error => {
|
||||
console.error(error)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@@ -1,9 +1,9 @@
|
||||
const { API_DOMAIN, REQUEST_TIMEOUT } = require('./config')
|
||||
const request = require('./request')
|
||||
|
||||
function normalizeUploadResponse(response, fallbackMessage) {
|
||||
function normalizeUploadResponse(response, fallbackMessage, url) {
|
||||
if (response.statusCode === 401) {
|
||||
throw new Error('登录已过期,请重新登录')
|
||||
throw request.handleUnauthorized({ data: response.data }, url)
|
||||
}
|
||||
if (response.statusCode >= 400) {
|
||||
const message = response.data && response.data.message ? response.data.message : fallbackMessage
|
||||
@@ -59,8 +59,16 @@ function uploadFile(options) {
|
||||
header: signatureHeaders,
|
||||
success(response) {
|
||||
try {
|
||||
const data = response.data ? preserveResponseId(response.data, JSON.parse(response.data)) : {}
|
||||
resolve(normalizeUploadResponse({ ...response, data }, options.errorMessage || '上传失败'))
|
||||
let parsedData = {}
|
||||
if (response.data) {
|
||||
try {
|
||||
parsedData = JSON.parse(response.data)
|
||||
} catch (error) {
|
||||
if (response.statusCode !== 401) throw error
|
||||
}
|
||||
}
|
||||
const data = preserveResponseId(response.data, parsedData)
|
||||
resolve(normalizeUploadResponse({ ...response, data }, options.errorMessage || '上传失败', options.url))
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
|
||||
@@ -5,16 +5,30 @@ global.REQUEST_TIMEOUT = 1000
|
||||
global.ENABLE_REQUEST_SIGNING = false
|
||||
|
||||
let uploadOptions
|
||||
const navigations = []
|
||||
let clearedSessions = 0
|
||||
global.wx = {
|
||||
getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }),
|
||||
getDeviceInfo: () => ({ platform: 'devtools' }),
|
||||
getStorageSync: () => ({}),
|
||||
setStorageSync: () => {},
|
||||
removeStorageSync: () => {},
|
||||
showToast: () => {},
|
||||
reLaunch: options => navigations.push(options.url),
|
||||
uploadFile(options) {
|
||||
uploadOptions = options
|
||||
if (options.filePath === '/tmp/expired.png') {
|
||||
options.success({ statusCode: 401, data: '{"message":"登录已过期"}' })
|
||||
return
|
||||
}
|
||||
options.success({
|
||||
statusCode: 200,
|
||||
data: '{"code":200,"data":{"fileId":9223372036854775001,"id":9223372036854775002}}'
|
||||
})
|
||||
}
|
||||
}
|
||||
global.getApp = () => ({ clearSession() { clearedSessions += 1 } })
|
||||
global.setTimeout = callback => { callback(); return 1 }
|
||||
|
||||
const { uploadFile } = require('./upload')
|
||||
|
||||
@@ -29,6 +43,14 @@ async function run() {
|
||||
assert.strictEqual(uploadOptions.url, 'http://127.0.0.1:80/api/user/workbench/register/avatar')
|
||||
assert.strictEqual(result.fileId, '9223372036854775001')
|
||||
assert.strictEqual(result.id, '9223372036854775002')
|
||||
|
||||
await assert.rejects(uploadFile({
|
||||
url: '/object-storage-file/upload',
|
||||
filePath: '/tmp/expired.png',
|
||||
name: 'file'
|
||||
}), /登录已过期/)
|
||||
assert.strictEqual(clearedSessions, 1)
|
||||
assert.deepStrictEqual(navigations, ['/pages/login/index'])
|
||||
}
|
||||
|
||||
run().catch(error => {
|
||||
|
||||
Reference in New Issue
Block a user