Files
MailUI4Agents/client/harmony/entry/src/main/ets/api/AuthApi.ets

106 lines
2.7 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* 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<Me> {
const payload: LoginPayload = new LoginPayload();
payload.username = username;
payload.password = password;
// Cookie 由 http 模块自动管理;此处仍拿回 user
const resp = await this.client.post<MeResponse>('/auth/login', payload, false);
return resp.user;
}
/** 用户密钥登录(Bearer 模式):直接用 key 调 /auth/me */
async loginWithKey(key: string): Promise<Me> {
this.client.setToken(key);
try {
const resp = await this.client.get<MeResponse>('/auth/me');
await this.client.persistToken(key);
return resp.user;
} catch (e) {
this.client.clearAuth();
throw e as ApiError;
}
}
/** 当前用户 */
async me(): Promise<Me> {
const resp = await this.client.get<MeResponse>('/auth/me');
return resp.user;
}
/** 退出登录 */
async logout(): Promise<void> {
try {
const empty: EmptyPayload = new EmptyPayload();
await this.client.post<EmptyPayload>('/auth/logout', empty);
} catch (e) {
// 忽略退出失败,本地清 token
}
this.client.clearAuth();
}
/** 创建客户端密钥 */
async createKey(label: string): Promise<UserKey> {
const payload: CreateKeyPayload = new CreateKeyPayload();
payload.label = label;
const resp = await this.client.post<CreateKeyResponse>('/me/keys', payload);
return resp.key;
}
/** 我的密钥列表 */
async listKeys(): Promise<UserKey[]> {
const resp = await this.client.get<KeyListResponse>('/me/keys');
return resp.keys;
}
/** 吊销密钥 */
async revokeKey(keyId: string): Promise<void> {
await this.client.del<Object>('/me/keys/' + keyId);
}
}