Add Auth for WebPage and APIs

This commit is contained in:
Raymond Zhou 2025-03-09 12:19:58 +08:00
parent e6b87f89ec
commit 5e6d0e0ee6
27 changed files with 15384 additions and 1720 deletions

View file

@ -1,4 +1,5 @@
import { Message } from '@/components/ChatWindow';
import { getApiUrl, post } from './api';
export const getSuggestions = async (chatHisory: Message[]) => {
const chatModel = localStorage.getItem('chatModel');
@ -7,12 +8,9 @@ export const getSuggestions = async (chatHisory: Message[]) => {
const customOpenAIKey = localStorage.getItem('openAIApiKey');
const customOpenAIBaseURL = localStorage.getItem('openAIBaseURL');
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/suggestions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
const data = await post<{ suggestions: string[] }>(
getApiUrl('/suggestions'),
{
chatHistory: chatHisory,
chatModel: {
provider: chatModelProvider,
@ -22,10 +20,8 @@ export const getSuggestions = async (chatHisory: Message[]) => {
customOpenAIBaseURL,
}),
},
}),
});
const data = (await res.json()) as { suggestions: string[] };
}
);
return data.suggestions;
};

96
ui/lib/api.ts Normal file
View file

@ -0,0 +1,96 @@
/**
* API请求工具函数
*/
// 基本API请求函数
export async function fetchWithToken(
url: string,
options: RequestInit = {}
): Promise<Response> {
// 从本地存储获取令牌
const token = localStorage.getItem('authToken');
// 准备请求头
const headers = {
'Content-Type': 'application/json',
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
...options.headers,
};
// 发送请求
return fetch(url, {
...options,
headers,
});
}
// GET请求
export async function get<T>(url: string, options: RequestInit = {}): Promise<T> {
const response = await fetchWithToken(url, {
method: 'GET',
...options,
});
if (!response.ok) {
throw new Error(`API请求失败: ${response.status}`);
}
return response.json();
}
// POST请求
export async function post<T>(
url: string,
data: any,
options: RequestInit = {}
): Promise<T> {
const response = await fetchWithToken(url, {
method: 'POST',
body: JSON.stringify(data),
...options,
});
if (!response.ok) {
throw new Error(`API请求失败: ${response.status}`);
}
return response.json();
}
// PUT请求
export async function put<T>(
url: string,
data: any,
options: RequestInit = {}
): Promise<T> {
const response = await fetchWithToken(url, {
method: 'PUT',
body: JSON.stringify(data),
...options,
});
if (!response.ok) {
throw new Error(`API请求失败: ${response.status}`);
}
return response.json();
}
// DELETE请求
export async function del<T>(url: string, options: RequestInit = {}): Promise<T> {
const response = await fetchWithToken(url, {
method: 'DELETE',
...options,
});
if (!response.ok) {
throw new Error(`API请求失败: ${response.status}`);
}
return response.json();
}
// 获取完整API URL
export function getApiUrl(path: string): string {
return `${process.env.NEXT_PUBLIC_API_URL}${path.startsWith('/') ? path : `/${path}`}`;
}