diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 95a22c1..e2fdc6d 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1,5 +1,10 @@ const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:8051'; +function authHeaders(): Record { + const token = localStorage.getItem('auth_token'); + return token ? { Authorization: `Bearer ${token}` } : {}; +} + export interface ChatResponse { response: string; sources?: Array<{ @@ -30,7 +35,7 @@ export async function chat( ): Promise { const res = await fetch(`${API_BASE}/api/kb/${kbName}/chat`, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: { 'Content-Type': 'application/json', ...authHeaders() }, body: JSON.stringify({ query, use_hybrid: options?.useHybrid ?? false, @@ -47,7 +52,7 @@ export async function chat( } export async function getKBStats(kbName: string): Promise { - const res = await fetch(`${API_BASE}/api/kb/${kbName}/stats`); + const res = await fetch(`${API_BASE}/api/kb/${kbName}/stats`, { headers: authHeaders() }); if (!res.ok) { throw new Error(`Failed to get KB stats: ${res.statusText}`); } @@ -55,7 +60,7 @@ export async function getKBStats(kbName: string): Promise { } export async function listDocuments(kbName: string): Promise { - const res = await fetch(`${API_BASE}/api/kb/${kbName}/documents`); + const res = await fetch(`${API_BASE}/api/kb/${kbName}/documents`, { headers: authHeaders() }); if (!res.ok) { throw new Error(`Failed to list documents: ${res.statusText}`); } @@ -69,6 +74,7 @@ export async function uploadDocument(kbName: string, file: File): Promise const res = await fetch(`${API_BASE}/api/kb/${kbName}/upload`, { method: 'POST', + headers: authHeaders(), body: formData, }); @@ -80,6 +86,7 @@ export async function uploadDocument(kbName: string, file: File): Promise export async function deleteDocument(kbName: string, filename: string): Promise { const res = await fetch(`${API_BASE}/api/kb/${kbName}/documents/${encodeURIComponent(filename)}`, { method: 'DELETE', + headers: authHeaders(), }); if (!res.ok) { diff --git a/frontend/src/lib/auth.tsx b/frontend/src/lib/auth.tsx index 7693120..8e83fb7 100644 --- a/frontend/src/lib/auth.tsx +++ b/frontend/src/lib/auth.tsx @@ -1,7 +1,21 @@ import { createContext, useContext, useState, useEffect, ReactNode } from 'react'; +import axios from 'axios'; const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:8051'; +// Every component that talks to the API via axios imports the same default +// instance, so registering the interceptor once here attaches the stored +// token everywhere - without it, auth only ever covers the two fetch() calls +// in this file, and every axios-based request (projects, kanban, hooks, +// most of the app) goes out unauthenticated. +axios.interceptors.request.use((config) => { + const token = localStorage.getItem('auth_token'); + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + return config; +}); + interface AuthContextType { isAuthenticated: boolean; isAuthEnabled: boolean; diff --git a/mcp_server/auth.py b/mcp_server/auth.py index 4b7695f..b9e6b18 100644 --- a/mcp_server/auth.py +++ b/mcp_server/auth.py @@ -21,7 +21,12 @@ ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 7 days # Security -security = HTTPBearer() +# auto_error=False: let get_current_user itself decide whether a missing +# token is OK (auth not configured -> guest) or a 401 (auth configured). +# The HTTPBearer default (auto_error=True) rejects any request with no +# Authorization header before get_current_user's body ever runs, which +# breaks the "auth disabled by default" behavior entirely. +security = HTTPBearer(auto_error=False) def verify_password(plain_password: str, hashed_password: str) -> bool: @@ -101,7 +106,7 @@ def decode_access_token(token: str) -> Optional[dict]: return None -def get_current_user(credentials: HTTPAuthorizationCredentials = Security(security)) -> dict: +def get_current_user(credentials: Optional[HTTPAuthorizationCredentials] = Security(security)) -> dict: """ Dependency to get the current authenticated user. Use in FastAPI routes: current_user = Depends(get_current_user) @@ -112,6 +117,13 @@ def get_current_user(credentials: HTTPAuthorizationCredentials = Security(securi if not creds: return {"email": "guest", "auth_disabled": True} + if credentials is None: + raise HTTPException( + status_code=401, + detail="Not authenticated", + headers={"WWW-Authenticate": "Bearer"}, + ) + token = credentials.credentials payload = decode_access_token(token)