Files

50 lines
2.2 KiB
Plaintext
Raw Permalink Normal View History

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'
export async function requestSmsCode(phone: string): Promise<boolean> {
await requestJson('/auth/sms-code', 'POST', { phone, purpose: 'login' })
return true
}
export function acceptSession(result: UTSJSONObject, phone: string): string {
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
}
export async function loginWithSms(phone: string, code: string): Promise<string> {
return acceptSession(await requestSmsLogin(phone, code), phone)
}
export async function loginWithPassword(phone: string, password: string): Promise<string> {
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 })
}
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()
}