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