mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 19:00:02 +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
78 lines
2.6 KiB
TypeScript
78 lines
2.6 KiB
TypeScript
// API configuration and utility functions
|
|
|
|
// Get API base URL from environment variable.
|
|
// The launcher injects NEXT_PUBLIC_API_BASE from the canonical project-root `.env`.
|
|
export const API_BASE_URL =
|
|
process.env.NEXT_PUBLIC_API_BASE ||
|
|
(() => {
|
|
if (typeof window !== "undefined") {
|
|
console.error("NEXT_PUBLIC_API_BASE is not set.");
|
|
console.error(
|
|
"Please configure NEXT_PUBLIC_API_BASE in your environment and restart the application.",
|
|
);
|
|
console.error(
|
|
"Run python scripts/start_tour.py to rebuild your local setup if needed.",
|
|
);
|
|
}
|
|
throw new Error(
|
|
"NEXT_PUBLIC_API_BASE is not configured. Please set it in your environment and restart.",
|
|
);
|
|
})();
|
|
|
|
/**
|
|
* Construct a full API URL from a path
|
|
* @param path - API path (e.g., '/api/v1/knowledge/list')
|
|
* @returns Full URL (e.g., 'http://localhost:8001/api/v1/knowledge/list')
|
|
*/
|
|
export function apiUrl(path: string): string {
|
|
// Remove leading slash if present to avoid double slashes
|
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
|
|
// Remove trailing slash from base URL if present
|
|
const base = API_BASE_URL.endsWith("/")
|
|
? API_BASE_URL.slice(0, -1)
|
|
: API_BASE_URL;
|
|
|
|
return `${base}${normalizedPath}`;
|
|
}
|
|
|
|
/**
|
|
* Construct a WebSocket URL from a path
|
|
* @param path - WebSocket path (e.g., '/api/v1/solve')
|
|
* @returns WebSocket URL (e.g., 'ws://localhost:8001/api/v1/ws')
|
|
*/
|
|
export function wsUrl(path: string): string {
|
|
// Security Hardening: Convert http to ws and https to wss.
|
|
// In production environments (where API_BASE_URL starts with https), this ensures secure websockets.
|
|
const base = API_BASE_URL.replace(/^http:/, "ws:").replace(/^https:/, "wss:");
|
|
|
|
// Remove leading slash if present to avoid double slashes
|
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
|
|
// Remove trailing slash from base URL if present
|
|
const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
|
|
|
|
return `${normalizedBase}${normalizedPath}`;
|
|
}
|
|
|
|
const AUTH_ENABLED = process.env.NEXT_PUBLIC_AUTH_ENABLED === "true";
|
|
|
|
/**
|
|
* Authenticated fetch wrapper. Behaves identically to `fetch` but automatically
|
|
* redirects to /login when the backend returns 401 (expired / invalid token).
|
|
*/
|
|
export async function apiFetch(
|
|
input: RequestInfo | URL,
|
|
init?: RequestInit,
|
|
): Promise<Response> {
|
|
const res = await fetch(input, { credentials: "include", ...init });
|
|
|
|
if (res.status === 401 && AUTH_ENABLED && typeof window !== "undefined") {
|
|
const next = encodeURIComponent(window.location.pathname);
|
|
window.location.href = `/login?next=${next}`;
|
|
return new Promise(() => {});
|
|
}
|
|
|
|
return res;
|
|
}
|