feat(admin): Complete Phase 3.5.1-3.5.4 Prompt Management System (83%)
Summary: - Implement Prompt management infrastructure and core services - Build admin portal frontend with light theme - Integrate CodeMirror 6 editor for non-technical users Phase 3.5.1: Infrastructure Setup - Create capability_schema for Prompt storage - Add prompt_templates and prompt_versions tables - Add prompt:view/edit/debug/publish permissions - Migrate RVW prompts to database (RVW_EDITORIAL, RVW_METHODOLOGY) Phase 3.5.2: PromptService Core - Implement gray preview logic (DRAFT for debuggers, ACTIVE for users) - Module-level debug control (setDebugMode) - Handlebars template rendering - Variable extraction and validation (extractVariables, validateVariables) - Three-level disaster recovery (database -> cache -> hardcoded fallback) Phase 3.5.3: Management API - 8 RESTful endpoints (/api/admin/prompts/*) - Permission control (PROMPT_ENGINEER can edit, SUPER_ADMIN can publish) Phase 3.5.4: Frontend Management UI - Build admin portal architecture (AdminLayout, OrgLayout) - Add route system (/admin/*, /org/*) - Implement PromptListPage (filter, search, debug switch) - Implement PromptEditor (CodeMirror 6 simplified for clinical users) - Implement PromptEditorPage (edit, save, publish, test, version history) Technical Details: - Backend: 6 files, ~2044 lines (prompt.service.ts 596 lines) - Frontend: 9 files, ~1735 lines (PromptEditorPage.tsx 399 lines) - CodeMirror 6: Line numbers, auto-wrap, variable highlight, search, undo/redo - Chinese-friendly: 15px font, 1.8 line-height, system fonts Next Step: Phase 3.5.5 - Integrate RVW module with PromptService Tested: Backend API tests passed (8/8), Frontend pending user testing Status: Ready for Phase 3.5.5 RVW integration
This commit is contained in:
242
frontend-v2/src/framework/auth/api.ts
Normal file
242
frontend-v2/src/framework/auth/api.ts
Normal file
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* 认证API模块
|
||||
*/
|
||||
|
||||
import type {
|
||||
ApiResponse,
|
||||
LoginResponse,
|
||||
AuthUser,
|
||||
TokenInfo,
|
||||
PasswordLoginRequest,
|
||||
CodeLoginRequest,
|
||||
ChangePasswordRequest,
|
||||
} from './types';
|
||||
|
||||
// API基础URL
|
||||
const API_BASE = '/api/v1/auth';
|
||||
|
||||
/**
|
||||
* 存储Token到localStorage
|
||||
*/
|
||||
export function saveTokens(tokens: TokenInfo): void {
|
||||
localStorage.setItem('accessToken', tokens.accessToken);
|
||||
localStorage.setItem('refreshToken', tokens.refreshToken);
|
||||
localStorage.setItem('tokenExpiresAt', String(Date.now() + tokens.expiresIn * 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从localStorage获取Token
|
||||
*/
|
||||
export function getAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken');
|
||||
}
|
||||
|
||||
export function getRefreshToken(): string | null {
|
||||
return localStorage.getItem('refreshToken');
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除Token
|
||||
*/
|
||||
export function clearTokens(): void {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('tokenExpiresAt');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储用户信息
|
||||
*/
|
||||
export function saveUser(user: AuthUser): void {
|
||||
localStorage.setItem('user', JSON.stringify(user));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取存储的用户信息
|
||||
*/
|
||||
export function getSavedUser(): AuthUser | null {
|
||||
const userStr = localStorage.getItem('user');
|
||||
if (!userStr) return null;
|
||||
try {
|
||||
return JSON.parse(userStr);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查Token是否过期
|
||||
*/
|
||||
export function isTokenExpired(): boolean {
|
||||
const expiresAt = localStorage.getItem('tokenExpiresAt');
|
||||
if (!expiresAt) return true;
|
||||
return Date.now() > Number(expiresAt) - 60000; // 提前1分钟判断为过期
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带认证的fetch
|
||||
*/
|
||||
async function authFetch<T>(
|
||||
url: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<ApiResponse<T>> {
|
||||
const token = getAccessToken();
|
||||
|
||||
const headers: HeadersInit = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers || {}),
|
||||
};
|
||||
|
||||
if (token) {
|
||||
(headers as Record<string, string>)['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || '请求失败');
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 密码登录
|
||||
*/
|
||||
export async function loginWithPassword(request: PasswordLoginRequest): Promise<LoginResponse> {
|
||||
const response = await authFetch<LoginResponse>(`${API_BASE}/login/password`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
throw new Error(response.message || '登录失败');
|
||||
}
|
||||
|
||||
// 保存Token和用户信息
|
||||
saveTokens(response.data.tokens);
|
||||
saveUser(response.data.user);
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证码登录
|
||||
*/
|
||||
export async function loginWithCode(request: CodeLoginRequest): Promise<LoginResponse> {
|
||||
const response = await authFetch<LoginResponse>(`${API_BASE}/login/code`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
throw new Error(response.message || '登录失败');
|
||||
}
|
||||
|
||||
// 保存Token和用户信息
|
||||
saveTokens(response.data.tokens);
|
||||
saveUser(response.data.user);
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送验证码
|
||||
*/
|
||||
export async function sendVerificationCode(
|
||||
phone: string,
|
||||
type: 'LOGIN' | 'RESET_PASSWORD' = 'LOGIN'
|
||||
): Promise<{ expiresIn: number }> {
|
||||
const response = await authFetch<{ message: string; expiresIn: number }>(
|
||||
`${API_BASE}/verification-code`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, type }),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
throw new Error(response.message || '发送失败');
|
||||
}
|
||||
|
||||
return { expiresIn: response.data.expiresIn };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前用户信息
|
||||
*/
|
||||
export async function getCurrentUser(): Promise<AuthUser> {
|
||||
const response = await authFetch<AuthUser>(`${API_BASE}/me`);
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
throw new Error(response.message || '获取用户信息失败');
|
||||
}
|
||||
|
||||
// 更新本地存储
|
||||
saveUser(response.data);
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改密码
|
||||
*/
|
||||
export async function changePassword(request: ChangePasswordRequest): Promise<void> {
|
||||
const response = await authFetch<{ message: string }>(`${API_BASE}/change-password`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(response.message || '修改密码失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新Token
|
||||
*/
|
||||
export async function refreshAccessToken(): Promise<TokenInfo> {
|
||||
const refreshToken = getRefreshToken();
|
||||
|
||||
if (!refreshToken) {
|
||||
throw new Error('无RefreshToken');
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
clearTokens();
|
||||
throw new Error(data.message || '刷新Token失败');
|
||||
}
|
||||
|
||||
// 保存新Token
|
||||
saveTokens(data.data);
|
||||
|
||||
return data.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登出
|
||||
*/
|
||||
export async function logout(): Promise<void> {
|
||||
try {
|
||||
await authFetch(`${API_BASE}/logout`, { method: 'POST' });
|
||||
} catch {
|
||||
// 忽略登出API错误
|
||||
} finally {
|
||||
clearTokens();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user