mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 19:19:36 +08:00
Closes #227. Auth is disabled by default (AUTH_ENABLED=false) so localhost usage is unaffected. Set AUTH_ENABLED=true + NEXT_PUBLIC_AUTH_ENABLED=true to require login when hosting publicly. Backend - New deeptutor/services/auth.py: bcrypt password hashing, JWT create/decode, multi-user JSON store with role + created_at schema, auto-migration of old flat-hash format, first-user → admin bootstrap - New deeptutor/api/routers/auth.py: require_auth / require_admin FastAPI dependencies; public endpoints /login /logout /status /register /is_first_user; admin-only /users /users/{u}/role - deeptutor/api/main.py: Depends(require_auth) applied to all 14 protected routers - deeptutor/api/routers/unified_ws.py: cookie-based JWT check before ws.accept() when AUTH_ENABLED - Added bcrypt>=4.0.0 and python-jose[cryptography]>=3.3.0 to requirements/server.txt and pyproject.toml extras Frontend - web/middleware.ts: route protection; /login and /register are public - web/lib/api.ts: apiFetch wrapper — credentials:include + 401→login - web/lib/auth.ts: login/logout/fetchAuthStatus + register() + checkIsFirstUser() - web/lib/admin-api.ts: listUsers / deleteUser / setUserRole - web/lib/session-api.ts: credentials:include on all fetches; expectJson redirects to /login on 401 instead of throwing - web/app/(auth)/login/page.tsx: auto-redirects to /register when no users exist; shows success banner after registration - web/app/(auth)/register/page.tsx: new registration page with first-user admin notice and password confirmation - web/app/(admin)/admin/users/page.tsx: admin dashboard — user table with role toggle and delete; guards against self-demotion/deletion - AdminLink and LogoutButton hidden when AUTH_ENABLED=false - .env.example and README.md updated with auth vars and setup guide Made-with: Cursor
181 lines
4.4 KiB
TypeScript
181 lines
4.4 KiB
TypeScript
import type { StreamEvent } from "@/lib/unified-ws";
|
|
import { apiUrl } from "@/lib/api";
|
|
import { invalidateClientCache, withClientCache } from "@/lib/client-cache";
|
|
|
|
export interface SessionMessage {
|
|
id: number;
|
|
session_id: string;
|
|
role: "user" | "assistant" | "system";
|
|
content: string;
|
|
capability?: string;
|
|
events: StreamEvent[];
|
|
attachments: Array<{
|
|
type: string;
|
|
filename?: string;
|
|
base64?: string;
|
|
url?: string;
|
|
mime_type?: string;
|
|
}>;
|
|
created_at: number;
|
|
}
|
|
|
|
export interface SessionSummary {
|
|
id: string;
|
|
session_id: string;
|
|
title: string;
|
|
created_at: number;
|
|
updated_at: number;
|
|
message_count: number;
|
|
last_message: string;
|
|
status?:
|
|
| "idle"
|
|
| "running"
|
|
| "completed"
|
|
| "failed"
|
|
| "cancelled"
|
|
| "rejected";
|
|
active_turn_id?: string;
|
|
preferences?: {
|
|
capability?: string;
|
|
tools?: string[];
|
|
knowledge_bases?: string[];
|
|
language?: string;
|
|
};
|
|
}
|
|
|
|
export interface ActiveTurnSummary {
|
|
id: string;
|
|
turn_id: string;
|
|
session_id: string;
|
|
capability: string;
|
|
status: "running" | "completed" | "failed" | "cancelled" | "rejected";
|
|
error: string;
|
|
created_at: number;
|
|
updated_at: number;
|
|
finished_at?: number | null;
|
|
last_seq: number;
|
|
}
|
|
|
|
export interface SessionDetail {
|
|
id: string;
|
|
session_id: string;
|
|
title: string;
|
|
created_at: number;
|
|
updated_at: number;
|
|
status?:
|
|
| "idle"
|
|
| "running"
|
|
| "completed"
|
|
| "failed"
|
|
| "cancelled"
|
|
| "rejected";
|
|
active_turn_id?: string;
|
|
compressed_summary?: string;
|
|
summary_up_to_msg_id?: number;
|
|
preferences?: {
|
|
capability?: string;
|
|
tools?: string[];
|
|
knowledge_bases?: string[];
|
|
language?: string;
|
|
};
|
|
messages: SessionMessage[];
|
|
active_turns?: ActiveTurnSummary[];
|
|
}
|
|
|
|
export interface QuizResultItem {
|
|
question_id?: string;
|
|
question: string;
|
|
question_type?: string;
|
|
options?: Record<string, string>;
|
|
user_answer: string;
|
|
correct_answer: string;
|
|
explanation?: string;
|
|
difficulty?: string;
|
|
is_correct: boolean;
|
|
}
|
|
|
|
async function expectJson<T>(response: Response): Promise<T> {
|
|
if (response.status === 401 && typeof window !== "undefined") {
|
|
const next = encodeURIComponent(window.location.pathname);
|
|
window.location.href = `/login?next=${next}`;
|
|
return new Promise(() => {});
|
|
}
|
|
if (!response.ok) {
|
|
throw new Error(`Request failed: ${response.status}`);
|
|
}
|
|
return response.json() as Promise<T>;
|
|
}
|
|
|
|
export async function listSessions(
|
|
limit = 50,
|
|
offset = 0,
|
|
options?: { force?: boolean },
|
|
): Promise<SessionSummary[]> {
|
|
return withClientCache<SessionSummary[]>(
|
|
`sessions:${limit}:${offset}`,
|
|
async () => {
|
|
const response = await fetch(
|
|
apiUrl(`/api/v1/sessions?limit=${limit}&offset=${offset}`),
|
|
{
|
|
cache: "no-store",
|
|
credentials: "include",
|
|
},
|
|
);
|
|
const data = await expectJson<{ sessions: SessionSummary[] }>(response);
|
|
return data.sessions ?? [];
|
|
},
|
|
{
|
|
force: options?.force,
|
|
ttlMs: 15_000,
|
|
},
|
|
);
|
|
}
|
|
|
|
export async function getSession(sessionId: string): Promise<SessionDetail> {
|
|
const response = await fetch(apiUrl(`/api/v1/sessions/${sessionId}`), {
|
|
cache: "no-store",
|
|
credentials: "include",
|
|
});
|
|
return expectJson<SessionDetail>(response);
|
|
}
|
|
|
|
export async function updateSessionTitle(
|
|
sessionId: string,
|
|
title: string,
|
|
): Promise<SessionDetail> {
|
|
const response = await fetch(apiUrl(`/api/v1/sessions/${sessionId}`), {
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ title }),
|
|
});
|
|
const data = await expectJson<{ session: SessionDetail }>(response);
|
|
invalidateClientCache("sessions:");
|
|
return data.session;
|
|
}
|
|
|
|
export async function deleteSession(sessionId: string): Promise<void> {
|
|
const response = await fetch(apiUrl(`/api/v1/sessions/${sessionId}`), {
|
|
method: "DELETE",
|
|
credentials: "include",
|
|
});
|
|
await expectJson<{ deleted: boolean }>(response);
|
|
invalidateClientCache("sessions:");
|
|
}
|
|
|
|
export async function recordQuizResults(
|
|
sessionId: string,
|
|
answers: QuizResultItem[],
|
|
): Promise<void> {
|
|
const response = await fetch(
|
|
apiUrl(`/api/v1/sessions/${sessionId}/quiz-results`),
|
|
{
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ answers }),
|
|
},
|
|
);
|
|
await expectJson<{ recorded: boolean }>(response);
|
|
}
|