53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import { LOGIN_PAGE } from './config'
|
|
import { clearAuth, getAccessToken, isLoggedIn, saveTokens } from './token'
|
|
import type { AuthToken, WxLoginResult } from './api'
|
|
import { logout as apiLogout, wxSilentLogin } from './api'
|
|
|
|
/** 包装 wx.login,返回一次性 code */
|
|
export function wxLoginCode(): Promise<string> {
|
|
return new Promise<string>((resolve, reject) => {
|
|
wx.login({
|
|
success: (res) => {
|
|
if (res.code) {
|
|
resolve(res.code)
|
|
} else {
|
|
reject(new Error('微信登录失败:未获取到 code'))
|
|
}
|
|
},
|
|
fail: () => reject(new Error('微信登录失败,请重试'))
|
|
})
|
|
})
|
|
}
|
|
|
|
/** 保存后端签发的令牌 */
|
|
export function saveAuthToken(token: AuthToken): void {
|
|
saveTokens({ accessToken: token.accessToken, refreshToken: token.refreshToken })
|
|
}
|
|
|
|
/** 未登录时跳转登录页;返回是否已登录,供页面 onShow 短路 */
|
|
export function ensureLogin(): boolean {
|
|
if (isLoggedIn()) return true
|
|
wx.reLaunch({ url: LOGIN_PAGE })
|
|
return false
|
|
}
|
|
|
|
/** 微信静默登录:已绑定 openid 时直接返回令牌 */
|
|
export async function silentLogin(): Promise<WxLoginResult> {
|
|
const code = await wxLoginCode()
|
|
return wxSilentLogin(code)
|
|
}
|
|
|
|
/** 退出登录:先通知后端失效令牌,再清本地并回登录页 */
|
|
export async function logout(): Promise<void> {
|
|
const token = getAccessToken()
|
|
if (token) {
|
|
try {
|
|
await apiLogout(token)
|
|
} catch {
|
|
// 后端不可达也要清本地登录态
|
|
}
|
|
}
|
|
clearAuth()
|
|
wx.reLaunch({ url: LOGIN_PAGE })
|
|
}
|