fix:bug解决
This commit is contained in:
@@ -66,9 +66,18 @@ function isAmapOk(status?: string | number): boolean {
|
||||
return String(status) === '1'
|
||||
}
|
||||
|
||||
function parseAmapLocation(location?: string): { longitude: number; latitude: number } | null {
|
||||
if (!location || location === '[]') return null
|
||||
const [lngText, latText] = location.split(',')
|
||||
/** 高德部分字段在 JSON 里会是 [] 而非字符串,需统一转成文本再解析 */
|
||||
function amapFieldText(value: unknown): string {
|
||||
if (value == null) return ''
|
||||
if (Array.isArray(value)) return ''
|
||||
const text = String(value).trim()
|
||||
return text === '[]' ? '' : text
|
||||
}
|
||||
|
||||
function parseAmapLocation(location?: unknown): { longitude: number; latitude: number } | null {
|
||||
const text = amapFieldText(location)
|
||||
if (!text) return null
|
||||
const [lngText, latText] = text.split(',')
|
||||
const longitude = Number(lngText)
|
||||
const latitude = Number(latText)
|
||||
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null
|
||||
@@ -116,12 +125,15 @@ function mapPois(pois: AmapPoi[] | undefined): MapLocationPoint[] {
|
||||
if (!Array.isArray(pois)) return []
|
||||
const results: MapLocationPoint[] = []
|
||||
for (const poi of pois) {
|
||||
const name = poi.name?.trim()
|
||||
const name = amapFieldText(poi.name)
|
||||
if (!name) continue
|
||||
const coords = parseAmapLocation(poi.location)
|
||||
if (!coords) continue
|
||||
const region = [poi.pname, poi.cityname, poi.adname].filter(Boolean).join('')
|
||||
const address = poi.address?.trim() || region || name
|
||||
const region = [poi.pname, poi.cityname, poi.adname]
|
||||
.map((part) => amapFieldText(part))
|
||||
.filter(Boolean)
|
||||
.join('')
|
||||
const address = amapFieldText(poi.address) || region || name
|
||||
results.push({
|
||||
name,
|
||||
address,
|
||||
@@ -136,11 +148,11 @@ function mapInputTips(body: AmapInputTipsResponse | null): MapLocationPoint[] {
|
||||
if (!body || !isAmapOk(body.status) || !Array.isArray(body.tips)) return []
|
||||
const results: MapLocationPoint[] = []
|
||||
for (const tip of body.tips) {
|
||||
const name = tip.name?.trim()
|
||||
const name = amapFieldText(tip.name)
|
||||
if (!name) continue
|
||||
const coords = parseAmapLocation(tip.location)
|
||||
if (!coords) continue
|
||||
const address = tip.address?.trim() || tip.district?.trim() || name
|
||||
const address = amapFieldText(tip.address) || amapFieldText(tip.district) || name
|
||||
results.push({
|
||||
name,
|
||||
address,
|
||||
@@ -264,7 +276,8 @@ export async function searchAmapPlaces(
|
||||
}
|
||||
if (city) {
|
||||
textData.city = city
|
||||
textData.citylimit = 'true'
|
||||
// 仅作范围偏好,避免严格 citylimit 导致模糊词搜不到
|
||||
textData.citylimit = 'false'
|
||||
}
|
||||
|
||||
const [aroundBody, tipsBody, textBody] = await Promise.all([
|
||||
@@ -293,6 +306,29 @@ export async function searchAmapPlaces(
|
||||
return { places }
|
||||
}
|
||||
|
||||
if (city) {
|
||||
const [fallbackTips, fallbackText] = await Promise.all([
|
||||
requestAmap<AmapInputTipsResponse>('/v3/assistant/inputtips', {
|
||||
keywords: trimmed,
|
||||
datatype: 'all',
|
||||
...(location ? { location } : {}),
|
||||
}),
|
||||
requestAmap<AmapPlaceSearchResponse>('/v3/place/text', {
|
||||
keywords: trimmed,
|
||||
offset: '20',
|
||||
page: '1',
|
||||
extensions: 'base',
|
||||
}),
|
||||
])
|
||||
const fallbackPlaces = dedupePlaces([
|
||||
...mapInputTips(fallbackTips),
|
||||
...mapPois(fallbackText?.pois),
|
||||
])
|
||||
if (fallbackPlaces.length) {
|
||||
return { places: fallbackPlaces }
|
||||
}
|
||||
}
|
||||
|
||||
const failed = [aroundBody, tipsBody, textBody].find((item) => item && !isAmapOk(item.status))
|
||||
if (failed) {
|
||||
return { places: [], error: mapAmapError(failed) }
|
||||
|
||||
119
src/utils/auth-session.ts
Normal file
119
src/utils/auth-session.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { teardownMessageInbox } from '@/hooks/use-message-inbox'
|
||||
import { ApiError } from '@/utils/api-error'
|
||||
import { clearLocalUserData } from '@/utils/clear-local-user-data'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
|
||||
export const LOGIN_ROUTE = '/pages/login/index'
|
||||
|
||||
const DEFAULT_SESSION_EXPIRED_TOAST = '登录状态异常,请重新登录'
|
||||
|
||||
/** 未登录也可访问的页面(忘记密码、协议等) */
|
||||
const GUEST_ROUTE_PREFIXES = [
|
||||
'pages/login/',
|
||||
'pages/register/',
|
||||
'pages/forgot-password/',
|
||||
'pages/change-password/',
|
||||
'pages/agreement/',
|
||||
]
|
||||
|
||||
/** 这些接口的鉴权失败由页面自行处理,不做全局踢登 */
|
||||
const PUBLIC_AUTH_API_PREFIXES = [
|
||||
'/app/auth/login/',
|
||||
'/app/auth/sendSmsCode',
|
||||
'/app/auth/agreements',
|
||||
'/app/auth/agreement/detail',
|
||||
'/app/auth/register',
|
||||
]
|
||||
|
||||
let sessionRedirecting = false
|
||||
|
||||
export function isGuestAllowedRoute(route: string): boolean {
|
||||
const normalized = route.replace(/^\//, '')
|
||||
return GUEST_ROUTE_PREFIXES.some((prefix) => normalized.startsWith(prefix))
|
||||
}
|
||||
|
||||
export function isPublicAuthApi(path: string): boolean {
|
||||
const normalized = path.split('?')[0]
|
||||
return PUBLIC_AUTH_API_PREFIXES.some((prefix) => normalized.startsWith(prefix))
|
||||
}
|
||||
|
||||
export function isAuthSessionExpiredError(err: unknown): boolean {
|
||||
if (!(err instanceof ApiError)) return false
|
||||
if (err.code === 401) return true
|
||||
const message = err.message?.trim() ?? ''
|
||||
if (!message) return false
|
||||
return /登录状态|未登录|重新登录|token\s*无效|token\s*过期|认证失败|授权失败|令牌已失效|请先登录/i.test(message)
|
||||
}
|
||||
|
||||
export function resolveAuthSessionExpiredMessage(err: unknown): string {
|
||||
if (err instanceof ApiError) {
|
||||
const message = err.message?.trim()
|
||||
if (message && isAuthSessionExpiredError(err)) return message
|
||||
}
|
||||
return DEFAULT_SESSION_EXPIRED_TOAST
|
||||
}
|
||||
|
||||
export function shouldForceLoginOnAuthError(requestPath: string, err: unknown): boolean {
|
||||
if (!isAuthSessionExpiredError(err)) return false
|
||||
if (isPublicAuthApi(requestPath)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理本地登录态并回到登录页(改密 / 后台重置密码后 token 失效等场景)
|
||||
*/
|
||||
export function handleAuthSessionExpired(options?: {
|
||||
message?: string
|
||||
requestPath?: string
|
||||
/** 改密成功等场景:即使当前在忘记密码/设置密码页也强制进入登录页 */
|
||||
forceNavigateToLogin?: boolean
|
||||
}): void {
|
||||
if (options?.requestPath && isPublicAuthApi(options.requestPath)) return
|
||||
|
||||
const forceLogin = Boolean(options?.forceNavigateToLogin)
|
||||
if (sessionRedirecting && !forceLogin) return
|
||||
|
||||
sessionRedirecting = true
|
||||
teardownMessageInbox()
|
||||
clearLocalUserData({ preservePasswordRecord: true })
|
||||
|
||||
const toastTitle = options?.message?.trim() || DEFAULT_SESSION_EXPIRED_TOAST
|
||||
uni.showToast({ title: toastTitle, icon: 'none', duration: 2000 })
|
||||
|
||||
setTimeout(() => {
|
||||
const pages = getCurrentPages()
|
||||
const route = pages[pages.length - 1]?.route || ''
|
||||
if (forceLogin || !isGuestAllowedRoute(route)) {
|
||||
uni.reLaunch({ url: LOGIN_ROUTE })
|
||||
}
|
||||
setTimeout(() => {
|
||||
sessionRedirecting = false
|
||||
}, 500)
|
||||
}, 600)
|
||||
}
|
||||
|
||||
export function notifyAuthSessionExpired(err: unknown, requestPath: string): void {
|
||||
if (!shouldForceLoginOnAuthError(requestPath, err)) return
|
||||
handleAuthSessionExpired({
|
||||
message: resolveAuthSessionExpiredMessage(err),
|
||||
requestPath,
|
||||
})
|
||||
}
|
||||
|
||||
/** App 从后台回到前台:无 token 且不在访客页时强制登录 */
|
||||
export function ensureLoggedInOnForeground(): boolean {
|
||||
if (getStoredToken()) return true
|
||||
|
||||
const pages = getCurrentPages()
|
||||
const route = pages[pages.length - 1]?.route || ''
|
||||
if (isGuestAllowedRoute(route)) return false
|
||||
|
||||
if (!sessionRedirecting) {
|
||||
sessionRedirecting = true
|
||||
uni.reLaunch({ url: LOGIN_ROUTE })
|
||||
setTimeout(() => {
|
||||
sessionRedirecting = false
|
||||
}, 500)
|
||||
}
|
||||
return false
|
||||
}
|
||||
73
src/utils/clear-local-user-data.ts
Normal file
73
src/utils/clear-local-user-data.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { clearStoredCsToken, clearStoredToken, getStoredCsToken, getStoredToken, saveStoredCsToken, saveStoredToken } from '@/utils/auth-token'
|
||||
import {
|
||||
clearPasswordModifiedAt,
|
||||
exportPasswordModifiedRecord,
|
||||
PASSWORD_MODIFIED_RECORD_KEY,
|
||||
restorePasswordModifiedRecord,
|
||||
} from '@/utils/password-modified-at'
|
||||
import { clearPushCache } from '@/utils/message-push-cache'
|
||||
import { clearKbButtonsCache } from '@/pages/mine/support/support-kb-buttons-cache'
|
||||
import {
|
||||
clearCachedCsSessionId,
|
||||
clearCachedHistorySessionId,
|
||||
resetQueueWaitTracking,
|
||||
stopSupportMessagePollTimer,
|
||||
stopSupportPollTimer,
|
||||
stopSupportQueueTimer,
|
||||
} from '@/pages/mine/support/support-runtime'
|
||||
|
||||
const PENDING_PASSWORD_PHONE_KEY = 'czzj_password_modified_pending_phone'
|
||||
|
||||
function clearAllUniStorage(preserveKeys: string[] = []): void {
|
||||
try {
|
||||
const { keys = [] } = uni.getStorageInfoSync()
|
||||
for (const key of keys) {
|
||||
if (preserveKeys.includes(key)) continue
|
||||
uni.removeStorageSync(key)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export interface ClearLocalUserDataOptions {
|
||||
/** 改密后踢登、同账号重新登录时保留「上次修改」记录 */
|
||||
preservePasswordRecord?: boolean
|
||||
}
|
||||
|
||||
/** 登出 / 注销 / 登录态失效:清空本地用户数据(含密码修改时间、家庭/geo 缓存等) */
|
||||
export function clearLocalUserData(options?: ClearLocalUserDataOptions): void {
|
||||
const preservePassword = Boolean(options?.preservePasswordRecord)
|
||||
const passwordRecord = preservePassword ? exportPasswordModifiedRecord() : null
|
||||
const preserveKeys = preservePassword
|
||||
? [PASSWORD_MODIFIED_RECORD_KEY, PENDING_PASSWORD_PHONE_KEY]
|
||||
: []
|
||||
|
||||
stopSupportPollTimer()
|
||||
stopSupportMessagePollTimer()
|
||||
stopSupportQueueTimer()
|
||||
clearCachedCsSessionId()
|
||||
clearCachedHistorySessionId()
|
||||
clearKbButtonsCache()
|
||||
resetQueueWaitTracking()
|
||||
clearPushCache()
|
||||
if (!preservePassword) {
|
||||
clearPasswordModifiedAt()
|
||||
}
|
||||
clearAllUniStorage(preserveKeys)
|
||||
clearStoredToken()
|
||||
if (preservePassword) {
|
||||
restorePasswordModifiedRecord(passwordRecord)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 新账号登录成功:清空上一账号本地残留,但保留当前已写入的登录令牌。
|
||||
*/
|
||||
export function clearLocalUserDataPreservingAuth(): void {
|
||||
const token = getStoredToken()
|
||||
const csToken = getStoredCsToken()
|
||||
clearLocalUserData({ preservePasswordRecord: true })
|
||||
if (token) saveStoredToken(token)
|
||||
if (csToken) saveStoredCsToken(csToken)
|
||||
}
|
||||
@@ -1,17 +1,123 @@
|
||||
const STORAGE_KEY = 'czzj_password_modified_at'
|
||||
import { isSamePhone, normalizePhoneDigits } from '@/utils/validate'
|
||||
|
||||
/** 密码修改成功后记录时间戳 */
|
||||
export function markPasswordModified(at = Date.now()): void {
|
||||
uni.setStorageSync(STORAGE_KEY, at)
|
||||
const LEGACY_STORAGE_KEY = 'czzj_password_modified_at'
|
||||
export const PASSWORD_MODIFIED_RECORD_KEY = 'czzj_password_modified_record'
|
||||
const PENDING_BY_PHONE_KEY = 'czzj_password_modified_pending_phone'
|
||||
|
||||
const STORAGE_KEY = PASSWORD_MODIFIED_RECORD_KEY
|
||||
|
||||
interface PasswordModifiedRecord {
|
||||
userId: string
|
||||
at: number
|
||||
}
|
||||
|
||||
export function getPasswordModifiedAt(): number | null {
|
||||
const value = uni.getStorageSync(STORAGE_KEY)
|
||||
if (typeof value === 'number' && value > 0) return value
|
||||
if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value)
|
||||
interface PendingPasswordModifiedRecord {
|
||||
phone: string
|
||||
at: number
|
||||
}
|
||||
|
||||
function readRecord(): PasswordModifiedRecord | null {
|
||||
try {
|
||||
const raw = uni.getStorageSync(STORAGE_KEY) as PasswordModifiedRecord | string | number
|
||||
if (raw && typeof raw === 'object' && 'userId' in raw && 'at' in raw) {
|
||||
const userId = String((raw as PasswordModifiedRecord).userId).trim()
|
||||
const at = Number((raw as PasswordModifiedRecord).at)
|
||||
if (userId && at > 0) return { userId, at }
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 移除旧版全局时间戳(不区分账号,会导致注销后新账号误读) */
|
||||
export function purgeLegacyPasswordModifiedStorage(): void {
|
||||
try {
|
||||
uni.removeStorageSync(LEGACY_STORAGE_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
/** 密码修改成功后记录时间戳(必须绑定当前 userId) */
|
||||
export function markPasswordModified(userId: string | number, at = Date.now()): void {
|
||||
const id = String(userId).trim()
|
||||
if (!id) return
|
||||
purgeLegacyPasswordModifiedStorage()
|
||||
uni.setStorageSync(STORAGE_KEY, { userId: id, at })
|
||||
}
|
||||
|
||||
export function clearPasswordModifiedAt(): void {
|
||||
purgeLegacyPasswordModifiedStorage()
|
||||
try {
|
||||
uni.removeStorageSync(STORAGE_KEY)
|
||||
uni.removeStorageSync(PENDING_BY_PHONE_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function exportPasswordModifiedRecord(): PasswordModifiedRecord | null {
|
||||
return readRecord()
|
||||
}
|
||||
|
||||
export function restorePasswordModifiedRecord(record: PasswordModifiedRecord | null): void {
|
||||
if (!record?.userId || !record.at) return
|
||||
uni.setStorageSync(STORAGE_KEY, record)
|
||||
}
|
||||
|
||||
function readPendingByPhone(): PendingPasswordModifiedRecord | null {
|
||||
try {
|
||||
const raw = uni.getStorageSync(PENDING_BY_PHONE_KEY) as PendingPasswordModifiedRecord
|
||||
if (raw && typeof raw === 'object' && raw.phone && raw.at > 0) {
|
||||
return { phone: normalizePhoneDigits(String(raw.phone)), at: Number(raw.at) }
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 未登录改密时先按手机号暂存,登录后由 adoptPendingPasswordModifiedForUser 写入 userId */
|
||||
export function markPasswordModifiedPendingForPhone(phone: string, at = Date.now()): void {
|
||||
const normalized = normalizePhoneDigits(phone)
|
||||
if (!normalized) return
|
||||
purgeLegacyPasswordModifiedStorage()
|
||||
uni.setStorageSync(PENDING_BY_PHONE_KEY, { phone: normalized, at })
|
||||
}
|
||||
|
||||
export function adoptPendingPasswordModifiedForUser(
|
||||
userId: string | number,
|
||||
phone?: string,
|
||||
): number | null {
|
||||
const pending = readPendingByPhone()
|
||||
const boundPhone = phone?.trim() ? normalizePhoneDigits(phone) : ''
|
||||
if (!pending || !boundPhone || !isSamePhone(pending.phone, boundPhone)) return null
|
||||
markPasswordModified(userId, pending.at)
|
||||
try {
|
||||
uni.removeStorageSync(PENDING_BY_PHONE_KEY)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return pending.at
|
||||
}
|
||||
|
||||
/** 仅返回与当前 userId 匹配的记录;不匹配则视为残留并清除 */
|
||||
export function getPasswordModifiedAt(userId?: string | number | null): number | null {
|
||||
purgeLegacyPasswordModifiedStorage()
|
||||
|
||||
const currentUserId = userId != null ? String(userId).trim() : ''
|
||||
if (!currentUserId) return null
|
||||
|
||||
const record = readRecord()
|
||||
if (!record) return null
|
||||
if (record.userId !== currentUserId) {
|
||||
clearPasswordModifiedAt()
|
||||
return null
|
||||
}
|
||||
return record.at
|
||||
}
|
||||
|
||||
/** 展示「上次修改:刚刚 / 3天前」等文案 */
|
||||
export function formatPasswordModifiedDesc(at: number | null): string {
|
||||
if (!at) return '上次修改:暂无记录'
|
||||
|
||||
@@ -34,6 +34,8 @@ import iconMineNotify from '@/static/icon-mine-notify@2x.png'
|
||||
import iconMineOrder from '@/static/icon-mine-order@2x.png'
|
||||
import iconMineCoupon from '@/static/icon-mine-coupon@2x.png'
|
||||
import iconMineAddress from '@/static/icon-mine-address@2x.png'
|
||||
import iconNotifyFilterArrow from '@/static/icon-notify-filter-arrow.png'
|
||||
import iconSupportTime from '@/static/icon-support-time.png'
|
||||
|
||||
export const staticAssets = {
|
||||
logo: logoCenter,
|
||||
@@ -71,4 +73,6 @@ export const staticAssets = {
|
||||
iconMineOrder,
|
||||
iconMineCoupon,
|
||||
iconMineAddress,
|
||||
iconNotifyFilterArrow,
|
||||
iconSupportTime,
|
||||
} as const
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
export function normalizePhoneDigits(phone: string): string {
|
||||
return phone.replace(/\D/g, '')
|
||||
}
|
||||
|
||||
export function isValidPhone(phone: string): boolean {
|
||||
return /^1\d{10}$/.test(phone.trim())
|
||||
return /^1\d{10}$/.test(normalizePhoneDigits(phone))
|
||||
}
|
||||
|
||||
/** 比较两个手机号是否相同(忽略空格、分隔符) */
|
||||
export function isSamePhone(a: string, b: string): boolean {
|
||||
const left = normalizePhoneDigits(a)
|
||||
const right = normalizePhoneDigits(b)
|
||||
if (!left || !right) return false
|
||||
return left === right
|
||||
}
|
||||
|
||||
export function isValidSmsCode(code: string): boolean {
|
||||
return /^\d{4,6}$/.test(code.trim())
|
||||
}
|
||||
|
||||
/** 登录页密码为空时的提示 */
|
||||
export const LOGIN_PASSWORD_EMPTY_TOAST = '密码应为至少8位的数字、字母、特殊符号的组合'
|
||||
|
||||
/** 登录时输入校验(兼容历史短密码账号) */
|
||||
export function isValidPassword(password: string): boolean {
|
||||
return password.length >= 6 && password.length <= 32
|
||||
|
||||
Reference in New Issue
Block a user