2026-09-22 17:25:52 +08:00
|
|
|
import { API_BASE_URL, requestJson, saveSession, clearSession, getSession } from '@/services/api.uts'
|
|
|
|
|
export { API_BASE_URL } from '@/services/api.uts'
|
|
|
|
|
import { setUserStorage } from '@/services/storage.uts'
|
2026-09-20 10:52:10 +08:00
|
|
|
|
|
|
|
|
export async function requestSmsCode(phone: string): Promise<boolean> {
|
2026-09-22 17:25:52 +08:00
|
|
|
await requestJson('/auth/sms-code', 'POST', { phone, purpose: 'login' })
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 11:24:15 +08:00
|
|
|
export function acceptSession(result: UTSJSONObject, phone: string): string {
|
2026-09-22 17:25:52 +08:00
|
|
|
const token = result['token'] as string | null
|
|
|
|
|
const userId = result['userId'] as string | null
|
|
|
|
|
const expiresAt = result['expiresAt'] as string | null
|
|
|
|
|
if (token == null || userId == null || expiresAt == null) throw new Error('登录响应缺少会话信息')
|
|
|
|
|
saveSession(token, phone, userId, expiresAt)
|
|
|
|
|
const profile = result['profile'] as UTSJSONObject | null
|
|
|
|
|
if (profile != null) setUserStorage('finance.account.profile:' + phone, { nickname: profile['nickname'], avatar: profile['avatarUrl'] ?? '' })
|
|
|
|
|
return token
|
2026-09-20 10:52:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function loginWithSms(phone: string, code: string): Promise<string> {
|
2026-10-22 11:24:15 +08:00
|
|
|
return acceptSession(await requestSmsLogin(phone, code), phone)
|
2026-09-20 10:52:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function loginWithPassword(phone: string, password: string): Promise<string> {
|
2026-10-22 11:24:15 +08:00
|
|
|
return acceptSession(await requestPasswordLogin(phone, password), phone)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 页面先校验自身代次与原会话,再接受认证结果;迟到响应不能切换当前账户。
|
|
|
|
|
export async function requestSmsLogin(phone: string, code: string): Promise<UTSJSONObject> {
|
|
|
|
|
return await requestJson('/auth/sms-login', 'POST', { phone, code })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function requestPasswordLogin(phone: string, password: string): Promise<UTSJSONObject> {
|
|
|
|
|
return await requestJson('/auth/password-login', 'POST', { phone, password })
|
2026-09-20 10:52:10 +08:00
|
|
|
}
|
|
|
|
|
|
2026-09-22 17:25:52 +08:00
|
|
|
export async function logoutAccount(): Promise<void> {
|
|
|
|
|
const session = getSession()
|
|
|
|
|
if (session == null) { clearSession(); return }
|
|
|
|
|
try {
|
|
|
|
|
await requestJson('/auth/logout', 'POST', {})
|
|
|
|
|
} catch (error) {
|
|
|
|
|
// 401已清理会话,视为退出完成;网络失败保留会话以便重试撤销。
|
|
|
|
|
if (getSession() != null) throw error
|
|
|
|
|
}
|
|
|
|
|
const current = getSession()
|
|
|
|
|
if (current == null || current['token'] == session['token']) clearSession()
|
|
|
|
|
}
|