/* * AgentMail 鸿蒙客户端 — 认证 API * POST /auth/login / logout / GET /auth/me / POST /me/keys */ import { ApiClient, ApiError } from './ApiClient'; import { Me, UserKey } from '../model/Models'; /** 登录请求体 */ export class LoginPayload { username: string = ''; password: string = ''; } /** 创建密钥请求体 */ export class CreateKeyPayload { label: string = ''; key_type: string = 'permanent'; expires_hours: number = 0; } /** 登录响应(含用户) */ export class MeResponse { user: Me = new Me(); } /** 创建密钥响应 */ export class CreateKeyResponse { key: UserKey = new UserKey(); } /** 密钥列表响应 */ export class KeyListResponse { keys: UserKey[] = []; } /** 空请求体(logout 等无 body 场景) */ export class EmptyPayload { empty: boolean = true; } export class AuthApi { private client: ApiClient; constructor(client: ApiClient) { this.client = client; } /** 账号密码登录(Cookie 模式) */ async login(username: string, password: string): Promise { const payload: LoginPayload = new LoginPayload(); payload.username = username; payload.password = password; // Cookie 由 http 模块自动管理;此处仍拿回 user const resp = await this.client.post('/auth/login', payload, false); return resp.user; } /** 用户密钥登录(Bearer 模式):直接用 key 调 /auth/me */ async loginWithKey(key: string): Promise { this.client.setToken(key); try { const resp = await this.client.get('/auth/me'); await this.client.persistToken(key); return resp.user; } catch (e) { this.client.clearAuth(); throw e as ApiError; } } /** 当前用户 */ async me(): Promise { const resp = await this.client.get('/auth/me'); return resp.user; } /** 退出登录 */ async logout(): Promise { try { const empty: EmptyPayload = new EmptyPayload(); await this.client.post('/auth/logout', empty); } catch (e) { // 忽略退出失败,本地清 token } this.client.clearAuth(); } /** 创建客户端密钥 */ async createKey(label: string): Promise { const payload: CreateKeyPayload = new CreateKeyPayload(); payload.label = label; const resp = await this.client.post('/me/keys', payload); return resp.key; } /** 我的密钥列表 */ async listKeys(): Promise { const resp = await this.client.get('/me/keys'); return resp.keys; } /** 吊销密钥 */ async revokeKey(keyId: string): Promise { await this.client.del('/me/keys/' + keyId); } }