Files
deerflow-code/frontend-web/src/core/note/auth.ts
T
2026-05-21 19:40:54 +08:00

95 lines
2.3 KiB
TypeScript

import { getNoteApiBaseURL } from "@/core/config";
const NOTE_AUTH_STORAGE_KEY = "deerflow.note.auth";
const NOTE_LOGIN_USERNAME = "dhk@qq.com";
const NOTE_LOGIN_PASSWORD = "1qaz@WSX";
export interface NoteAuth {
access_token: string;
token_type: string;
}
function isBrowser(): boolean {
return typeof window !== "undefined";
}
function assertNoteApiBaseURL(): string {
const baseURL = getNoteApiBaseURL();
if (!baseURL) {
throw new Error("未配置 VITE_NOTE_API_BASE_URL");
}
return baseURL;
}
export function getStoredNoteAuth(): NoteAuth | null {
if (!isBrowser()) {
return null;
}
const raw = window.localStorage.getItem(NOTE_AUTH_STORAGE_KEY);
if (!raw) {
return null;
}
try {
return JSON.parse(raw) as NoteAuth;
} catch {
return null;
}
}
export function setStoredNoteAuth(auth: NoteAuth): void {
if (!isBrowser()) {
return;
}
window.localStorage.setItem(NOTE_AUTH_STORAGE_KEY, JSON.stringify(auth));
}
export function clearStoredNoteAuth(): void {
if (!isBrowser()) {
return;
}
window.localStorage.removeItem(NOTE_AUTH_STORAGE_KEY);
}
export function getNoteAuthorizationHeader(auth: NoteAuth): string {
const token = auth.access_token.trim();
const tokenType = auth.token_type?.trim() || "Bearer";
return `${tokenType} ${token}`;
}
export async function loginNoteApi(): Promise<NoteAuth> {
const formData = new FormData();
formData.append("username", NOTE_LOGIN_USERNAME);
formData.append("password", NOTE_LOGIN_PASSWORD);
formData.append("grant_type", "password");
const response = await fetch(`${assertNoteApiBaseURL()}/auth/jwt/login`, {
method: "POST",
body: formData,
});
if (!response.ok) {
throw new Error(`笔记登录失败: ${response.status} ${response.statusText}`);
}
const data = (await response.json()) as Partial<NoteAuth>;
if (!data.access_token) {
throw new Error("笔记登录失败: 未返回 access_token");
}
const auth: NoteAuth = {
access_token: data.access_token,
token_type: data.token_type?.trim() || "bearer",
};
setStoredNoteAuth(auth);
return auth;
}
export async function ensureNoteAuth(): Promise<NoteAuth> {
const existing = getStoredNoteAuth();
if (existing?.access_token) {
return existing;
}
return loginNoteApi();
}