Files
doodle-mini/miniprogram/utils/auth.ts
T

57 lines
2.0 KiB
TypeScript

import { apiRequest } from '../services/api-request';
import {
cachedServerUser,
clearSession,
ensureSession,
getAuthContext,
updateSessionUser,
type ServerUser,
} from '../services/auth-session';
export type UserInfo = ServerUser;
export { ensureSession as ensureAuthenticated } from '../services/auth-session';
/** 用户摘要与新后端认证绑定,所有远端用户业务只使用本站用户 ID。 */
export async function getUser(): Promise<UserInfo> {
return (await ensureSession()).user;
}
/** 缓存只供展示,不能证明服务端仍认可当前凭证。 */
export function getCachedUser(): UserInfo | null {
try {
return cachedServerUser();
} catch {
return null;
}
}
/** 读取本人资料;GET /me 会按统一规则完成过期与 401 恢复。 */
export async function refreshUser(): Promise<UserInfo> {
const context = getAuthContext();
const user = await apiRequest<UserInfo>('/me');
if (getAuthContext().key !== context.key)
throw new Error('接口环境已变化,请重新操作');
return updateSessionUser(user, context);
}
/** 暂停账户自动恢复时保留标记,不能通过清缓存自动注册。 */
export function clearUser(blocked = false): void {
clearSession(blocked);
}
/** 仅供用户主动确认“重新开始使用账户”的动作调用,禁止在失败回调自动调用。 */
export async function startAccount(): Promise<UserInfo> {
return (await ensureSession(getAuthContext(), true, true)).user;
}
/** 本人资料更新只提交头像资产 ID,不允许传任意外链或用户身份字段。 */
export async function updateUserProfile(payload: {
nickName?: string;
avatarAssetId?: string | null;
}): Promise<UserInfo> {
const context = getAuthContext();
const user = await apiRequest<UserInfo>('/me/profile', {
method: 'PUT',
data: payload,
});
if (getAuthContext().key !== context.key)
throw new Error('接口环境已变化,请重新操作');
return updateSessionUser(user, context);
}