Files
Charon/frontend/src/context/AuthContext.tsx
T
GitHub Actions 032d475fba chore: remediate 61 Go linting issues and tighten pre-commit config
Complete lint remediation addressing errcheck, gosec, and staticcheck
violations across backend test files. Tighten pre-commit configuration
to prevent future blind spots.

Key Changes:
- Fix 61 Go linting issues (errcheck, gosec G115/G301/G304/G306, bodyclose)
- Add proper error handling for json.Unmarshal, os.Setenv, db.Close(), w.Write()
- Fix gosec G115 integer overflow with strconv.FormatUint
- Add #nosec annotations with justifications for test fixtures
- Fix SecurityService goroutine leaks (add Close() calls)
- Fix CrowdSec tar.gz non-deterministic ordering with sorted keys

Pre-commit Hardening:
- Remove test file exclusion from golangci-lint hook
- Add gosec to .golangci-fast.yml with critical checks (G101, G110, G305)
- Replace broad .golangci.yml exclusions with targeted path-specific rules
- Test files now linted on every commit

Test Fixes:
- Fix emergency route count assertions (1→2 for dual-port setup)
- Fix DNS provider service tests with proper mock setup
- Fix certificate service tests with deterministic behavior

Backend: 27 packages pass, 83.5% coverage
Frontend: 0 lint warnings, 0 TypeScript errors
Pre-commit: All 14 hooks pass (~37s)
2026-02-02 06:17:48 +00:00

130 lines
3.7 KiB
TypeScript

import { useState, useEffect, useCallback, type ReactNode, type FC } from 'react';
import client, { setAuthToken, setAuthErrorHandler } from '../api/client';
import { AuthContext, User } from './AuthContextValue';
export const AuthProvider: FC<{ children: ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Handle session expiry by clearing auth state and redirecting to login
const handleAuthError = useCallback(() => {
console.log('Session expired, redirecting to login');
localStorage.removeItem('charon_auth_token');
setAuthToken(null);
setUser(null);
// Use window.location for full page redirect to clear any stale state
if (window.location.pathname !== '/login') {
window.location.href = '/login';
}
}, []);
// Register auth error handler on mount
useEffect(() => {
setAuthErrorHandler(handleAuthError);
}, [handleAuthError]);
useEffect(() => {
const checkAuth = async () => {
try {
const stored = localStorage.getItem('charon_auth_token');
if (stored) {
setAuthToken(stored);
}
const response = await client.get('/auth/me');
setUser(response.data);
} catch {
setAuthToken(null);
setUser(null);
} finally {
setIsLoading(false);
}
};
checkAuth();
}, []);
const login = async (token?: string) => {
if (token) {
localStorage.setItem('charon_auth_token', token);
setAuthToken(token);
}
try {
const response = await client.get<User>('/auth/me');
setUser(response.data);
} catch (error) {
setUser(null);
setAuthToken(null);
localStorage.removeItem('charon_auth_token');
throw error;
}
};
const logout = async () => {
try {
await client.post('/auth/logout');
} catch (error) {
console.error("Logout failed", error);
}
localStorage.removeItem('charon_auth_token');
setAuthToken(null);
setUser(null);
};
const changePassword = async (oldPassword: string, newPassword: string) => {
try {
await client.post('/auth/change-password', {
old_password: oldPassword,
new_password: newPassword,
});
} catch (error: unknown) {
// Extract error message from API response
const message = error instanceof Error
? error.message
: typeof error === 'object' && error !== null && 'response' in error
? (error as { response?: { data?: { error?: string } } }).response?.data?.error || 'Password change failed'
: 'Password change failed';
throw new Error(message);
}
};
// Auto-logout logic
useEffect(() => {
if (!user) return;
const TIMEOUT_MS = 15 * 60 * 1000; // 15 minutes
let timeoutId: ReturnType<typeof setTimeout>;
const resetTimer = () => {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
console.log('Auto-logging out due to inactivity');
logout();
}, TIMEOUT_MS);
};
// Initial timer start
resetTimer();
// Event listeners for activity
const events = ['mousedown', 'keydown', 'scroll', 'touchstart'];
const handleActivity = () => resetTimer();
events.forEach(event => {
window.addEventListener(event, handleActivity);
});
return () => {
if (timeoutId) clearTimeout(timeoutId);
events.forEach(event => {
window.removeEventListener(event, handleActivity);
});
};
}, [user]);
return (
<AuthContext.Provider value={{ user, login, logout, changePassword, isAuthenticated: !!user, isLoading }}>
{children}
</AuthContext.Provider>
);
};