claude-os/frontend/src/lib/auth.tsx
Rosie Val 9298de1a49 Fix auth so it actually enforces, not just decorates
Two gaps found while wiring auth into the data routes:

1. mcp_server/auth.py: HTTPBearer() defaults to auto_error=True, which
   rejects any request with no Authorization header before
   get_current_user's own "auth not configured -> allow as guest"
   check ever runs. That meant turning on Depends(get_current_user)
   anywhere 401'd every request even with auth fully disabled.
   Switched to auto_error=False and handle the missing-credentials
   case explicitly inside get_current_user instead.

2. Frontend never actually sent the stored token on data requests.
   auth.tsx only attached it to its own /api/auth/me check; api.ts's
   fetch() calls (chat, stats, documents, upload, delete) and every
   axios call elsewhere in the app (projects, kanban, hooks) had no
   Authorization header at all. Added an authHeaders() helper in
   api.ts, and a single axios request interceptor in auth.tsx that
   attaches the token app-wide since every component imports the same
   default axios instance.

Known gap not addressed here: mcp_server/claude_code_mcp.py (the
code-forge stdio MCP server) calls the REST API with no token at all.
Harmless while auth is disabled (current state), but it will start
getting 401'd the moment CLAUDE_OS_EMAIL/PASSWORD are actually set -
needs a service-token bypass if that's ever turned on.
2026-08-22 15:46:45 -04:00

116 lines
3.5 KiB
TypeScript

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;
isLoading: boolean;
user: { email: string } | null;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isAuthEnabled, setIsAuthEnabled] = useState(true);
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState<{ email: string } | null>(null);
useEffect(() => {
checkAuthStatus();
}, []);
const checkAuthStatus = async () => {
try {
// Check if auth is enabled
const statusRes = await fetch(`${API_BASE}/api/auth/status`);
if (statusRes.ok) {
const statusData = await statusRes.json();
setIsAuthEnabled(statusData.auth_enabled);
if (!statusData.auth_enabled) {
setIsAuthenticated(true);
setIsLoading(false);
return;
}
}
// Check if user is already logged in
const token = localStorage.getItem('auth_token');
if (token) {
const meRes = await fetch(`${API_BASE}/api/auth/me`, {
headers: { Authorization: `Bearer ${token}` }
});
if (meRes.ok) {
const userData = await meRes.json();
setUser(userData);
setIsAuthenticated(true);
} else {
localStorage.removeItem('auth_token');
}
}
} catch (error) {
// If we can't reach the server, assume auth is disabled for local dev
console.warn('Could not check auth status:', error);
setIsAuthEnabled(false);
setIsAuthenticated(true);
} finally {
setIsLoading(false);
}
};
const login = async (email: string, password: string) => {
const res = await fetch(`${API_BASE}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
if (!res.ok) {
const error = await res.json();
throw new Error(error.detail || 'Login failed');
}
const data = await res.json();
localStorage.setItem('auth_token', data.access_token);
setUser({ email });
setIsAuthenticated(true);
};
const logout = () => {
localStorage.removeItem('auth_token');
setUser(null);
setIsAuthenticated(false);
};
return (
<AuthContext.Provider value={{ isAuthenticated, isAuthEnabled, isLoading, user, login, logout }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}