mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 15:11:04 +08:00
The frontend no longer bakes the backend URL into the bundle at build
time and mutates it with sed on every container start. Instead:
* web/lib/api.ts: apiUrl and wsUrl become one-line pass-throughs, so
the browser fetches relative paths through the frontend
(:3782/api/...). All existing call sites keep working unchanged.
* web/proxy.ts: catches /api/* and /ws/* and rewrites them to
DEEPTUTOR_API_BASE_URL at request time, reading
DEEPTUTOR_AUTH_ENABLED for the auth-redirect check.
* web/lib/auth.ts: switches from NEXT_PUBLIC_AUTH_ENABLED (build-time)
to DEEPTUTOR_AUTH_ENABLED (set by the entrypoint on every start).
* Dockerfile: drops the .env.local placeholder block, the sed -i in
start-frontend.sh, and the runtime API-base fallback chain. Adds
gosu, bakes a non-root 'deeptutor' user (UID 1000), and has the
entrypoint chown /app/data and export DEEPTUTOR_API_BASE_URL and
DEEPTUTOR_AUTH_ENABLED from data/user/settings/*.json on every
start. supervisord is now invoked under 'gosu deeptutor'.
* web/tests/api-resolve-base.test.ts: deleted (its 8 tests reference
resolveBase / isApiBasePlaceholder, both gone; apiUrl/wsUrl are
now pass-throughs so the rest is meaningless). The auth-redirect
test is updated to prime DEEPTUTOR_AUTH_ENABLED instead.
132 lines
3.8 KiB
TypeScript
132 lines
3.8 KiB
TypeScript
import { apiFetch, apiUrl, parseAuthEnabled } from "@/lib/api";
|
|
|
|
// ``DEEPTUTOR_AUTH_ENABLED`` is exported by the container entrypoint on every
|
|
// start (read from ``data/user/settings/auth.json``). ``parseAuthEnabled``
|
|
// evaluates it at runtime (not a ``=== "true"`` literal comparison) so the
|
|
// minifier cannot constant-fold the check. See lib/api.ts.
|
|
export const AUTH_ENABLED = parseAuthEnabled(
|
|
process.env.DEEPTUTOR_AUTH_ENABLED,
|
|
);
|
|
|
|
export interface AuthStatus {
|
|
enabled: boolean;
|
|
authenticated: boolean;
|
|
user_id?: string;
|
|
username?: string;
|
|
role?: string;
|
|
is_admin?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Call the backend to check whether the current session is authenticated.
|
|
* Returns null on network error so callers can decide how to handle it.
|
|
*/
|
|
export async function fetchAuthStatus(): Promise<AuthStatus | null> {
|
|
try {
|
|
const res = await apiFetch(apiUrl("/api/v1/auth/status"));
|
|
if (!res.ok) return null;
|
|
return res.json();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST credentials to the backend. Returns true on success.
|
|
*/
|
|
export async function login(
|
|
username: string,
|
|
password: string,
|
|
): Promise<{ ok: boolean; error?: string }> {
|
|
try {
|
|
const res = await apiFetch(apiUrl("/api/v1/auth/login"), {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ username, password }),
|
|
// A 401 here means "wrong credentials", not an expired session — handle it
|
|
// inline as a form error instead of triggering the global login redirect.
|
|
skipAuthRedirect: true,
|
|
});
|
|
|
|
if (res.ok) return { ok: true };
|
|
|
|
const data = await res.json().catch(() => ({}));
|
|
return { ok: false, error: extractDetail(data.detail) ?? "Login failed" };
|
|
} catch {
|
|
return { ok: false, error: "Could not reach the server" };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Normalise a FastAPI error detail to a plain string.
|
|
* FastAPI can return detail as a string (HTTPException) or as an array of
|
|
* validation error objects (422 Unprocessable Entity).
|
|
*/
|
|
function extractDetail(detail: unknown): string {
|
|
if (typeof detail === "string") return detail;
|
|
if (Array.isArray(detail) && detail.length > 0) {
|
|
const first = detail[0];
|
|
if (typeof first === "object" && first !== null && "msg" in first)
|
|
return String((first as { msg: unknown }).msg);
|
|
}
|
|
return "Request failed";
|
|
}
|
|
|
|
/**
|
|
* Register a new account. The first user to register becomes admin.
|
|
*/
|
|
export async function register(
|
|
username: string,
|
|
password: string,
|
|
): Promise<{
|
|
ok: boolean;
|
|
role?: string;
|
|
is_first_user?: boolean;
|
|
error?: string;
|
|
}> {
|
|
try {
|
|
const res = await apiFetch(apiUrl("/api/v1/auth/register"), {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ username, password }),
|
|
// Registration validation failures (e.g. 400/401) should surface inline
|
|
// rather than bounce the user through the global login redirect.
|
|
skipAuthRedirect: true,
|
|
});
|
|
|
|
const data = await res.json().catch(() => ({}));
|
|
if (res.ok)
|
|
return { ok: true, role: data.role, is_first_user: data.is_first_user };
|
|
return { ok: false, error: extractDetail(data.detail) };
|
|
} catch {
|
|
return { ok: false, error: "Could not reach the server" };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check whether the user store is empty (first user will become admin).
|
|
*/
|
|
export async function checkIsFirstUser(): Promise<boolean> {
|
|
try {
|
|
const res = await apiFetch(apiUrl("/api/v1/auth/is_first_user"));
|
|
if (!res.ok) return false;
|
|
const data = await res.json();
|
|
return Boolean(data.is_first_user);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST to the logout endpoint to clear the session cookie.
|
|
*/
|
|
export async function logout(): Promise<void> {
|
|
try {
|
|
await apiFetch(apiUrl("/api/v1/auth/logout"), {
|
|
method: "POST",
|
|
});
|
|
} catch {
|
|
// Ignore — we'll redirect regardless
|
|
}
|
|
}
|