auth.ts
5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/**
* 登录态与受保护接口的请求封装。
*
* token 由后端种在 httpOnly cookie 中,前端读不到也不需要读,
* 所有请求带上 `credentials: "include"` 即可自动携带。
*/
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";
export interface CurrentUser {
id: string;
username: string;
displayName: string;
phone: string | null;
role: string;
positionId: string | null;
positionName: string | null;
storeName: string | null;
}
export class UnauthorizedError extends Error {
constructor() {
super("未登录或登录已失效");
this.name = "UnauthorizedError";
}
}
/** 带凭据的 fetch。遇到 401 统一抛 UnauthorizedError,由调用方决定是否跳登录页。 */
export async function apiFetch(path: string, init: RequestInit = {}): Promise<Response> {
const response = await fetch(`${API_BASE}${path}`, {
...init,
credentials: "include",
headers: {
...(init.body ? { "Content-Type": "application/json" } : {}),
...(init.headers || {}),
},
});
if (response.status === 401) {
throw new UnauthorizedError();
}
return response;
}
/** 请求 JSON 接口,非 2xx 时抛出后端返回的 detail 文案。 */
export async function apiJson<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
const response = await apiFetch(path, init);
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const detail = (data as { detail?: string }).detail || `请求失败(${response.status})`;
throw new Error(detail);
}
return data as T;
}
export async function login(account: string, password: string): Promise<CurrentUser> {
const data = await apiJson<{ user: CurrentUser }>("/auth/login", {
method: "POST",
body: JSON.stringify({ account, password }),
});
return data.user;
}
export async function logout(): Promise<void> {
await apiFetch("/auth/logout", { method: "POST" }).catch(() => undefined);
}
/** 获取当前用户;未登录返回 null(不抛异常,便于页面做重定向判断)。 */
export async function fetchMe(): Promise<CurrentUser | null> {
try {
const data = await apiJson<{ user: CurrentUser }>("/auth/me");
return data.user;
} catch (error) {
if (error instanceof UnauthorizedError) return null;
throw error;
}
}
export async function changePassword(oldPassword: string, newPassword: string): Promise<void> {
await apiJson("/auth/change-password", {
method: "POST",
body: JSON.stringify({ oldPassword, newPassword }),
});
}
// ============================== 会话 ==============================
export interface SessionItem {
id: string;
title: string;
totalTurns: number;
status: string;
updatedAt: string | null;
createdAt: string | null;
}
export interface SessionMessage {
seq: number;
role: "user" | "assistant";
content: string;
reasoning: ReasoningStep[] | null;
createdAt: string | null;
}
/** 落库的思考步骤。工具返回正文不入库,只有 meta 里的成功标志与字节数。 */
export interface ReasoningStep {
id: string;
type: "thought" | "call" | "response";
name?: string | null;
content?: string;
meta?: { ok: boolean; bytes: number };
}
export async function listSessions(limit = 20, offset = 0) {
return apiJson<{ total: number; items: SessionItem[] }>(
`/sessions?limit=${limit}&offset=${offset}`
);
}
/** 新建会话。传 previousSessionId 可让后端对上一个会话触发收尾沉淀。 */
export async function createSession(previousSessionId?: string | null) {
return apiJson<{ id: string }>("/sessions", {
method: "POST",
body: JSON.stringify({ previousSessionId: previousSessionId || null }),
});
}
export async function fetchSessionMessages(sessionId: string) {
return apiJson<{ id: string; title: string; messages: SessionMessage[] }>(
`/sessions/${sessionId}/messages`
);
}
export async function deleteSession(sessionId: string) {
return apiJson(`/sessions/${sessionId}`, { method: "DELETE" });
}
export async function renameSession(sessionId: string, title: string) {
return apiJson(`/sessions/${sessionId}`, {
method: "PATCH",
body: JSON.stringify({ title }),
});
}
// ============================== 画像 ==============================
export interface ProfilePayload {
profileMd: string;
agentMd: string;
// 未剥离元信息的原文,供编辑器加载
profileMdRaw: string;
agentMdRaw: string;
profileGenerated: boolean;
profileVersion: number;
memoryStats: { chars: number; entries: number; maxChars: number };
}
export async function fetchProfile() {
return apiJson<ProfilePayload>("/profile");
}
export async function regenerateProfile() {
return apiJson("/profile/regenerate", { method: "POST" });
}
/** 用户本人编辑自己的用户画像 / 长期记忆。 */
export async function updateMyProfile(payload: { profileMd?: string; agentMd?: string }) {
return apiJson("/profile", { method: "PATCH", body: JSON.stringify(payload) });
}
export async function clearMemory() {
return apiJson("/profile/memory", { method: "DELETE" });
}
// ============================== 管理员:用户画像编辑 ==============================
export interface AdminUserProfile {
userId: string;
displayName: string;
profileMd: string;
agentMd: string;
profileGenerated: boolean;
profileVersion: number;
memoryStats: { chars: number; entries: number; maxChars: number };
}
export async function fetchUserProfile(userId: string) {
return apiJson<AdminUserProfile>(`/admin/users/${userId}/profile`);
}
export async function updateUserProfile(
userId: string,
payload: { profileMd?: string; agentMd?: string }
) {
return apiJson(`/admin/users/${userId}/profile`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
export async function regenerateUserProfile(userId: string) {
return apiJson(`/admin/users/${userId}/profile/regenerate`, { method: "POST" });
}