Files
cve-dashboard/frontend/src/contexts/AuthContext.js

181 lines
5.5 KiB
JavaScript
Raw Normal View History

import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';
// Known BU teams — must match backend helpers/teams.js
const KNOWN_TEAMS = ['STEAM', 'ACCESS-ENG', 'ACCESS-OPS', 'INTELDEV'];
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// Admin scope toggle — persisted in localStorage
const [adminScope, setAdminScope] = useState(
() => localStorage.getItem('admin_bu_scope') || 'my-teams'
);
// Check if user is authenticated on mount
const checkAuth = useCallback(async () => {
try {
const response = await fetch(`${API_BASE}/auth/me`, {
credentials: 'include'
});
if (response.ok) {
const data = await response.json();
setUser(data.user);
} else {
setUser(null);
}
} catch (err) {
console.error('Auth check error:', err);
setUser(null);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
checkAuth();
}, [checkAuth]);
// Login function
const login = async (username, password) => {
setError(null);
try {
const response = await fetch(`${API_BASE}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Login failed');
}
setUser(data.user);
return { success: true };
} catch (err) {
setError(err.message);
return { success: false, error: err.message };
}
};
// Logout function
const logout = async () => {
try {
await fetch(`${API_BASE}/auth/logout`, {
method: 'POST',
credentials: 'include'
});
} catch (err) {
console.error('Logout error:', err);
}
setUser(null);
};
// Check if user belongs to one of the specified groups
const isInGroup = (...groups) => user && groups.includes(user.group);
// Check if user can perform write operations (Admin or Standard_User)
const canWrite = () => isInGroup('Admin', 'Standard_User');
// Check if user can delete a resource
// Admin: always true; Standard_User: only if they own the resource; others: false
const canDelete = (resource) => {
if (!user) return false;
if (isInGroup('Admin')) return true;
if (!isInGroup('Standard_User')) return false;
return resource?.created_by === user.id;
};
// Check if user can export data
const canExport = () => isInGroup('Admin', 'Standard_User', 'Leadership');
// Check if user is admin
const isAdmin = () => isInGroup('Admin');
// -----------------------------------------------------------------------
// Multi-BU tenancy helpers
// -----------------------------------------------------------------------
// Whether the user has any BU teams assigned
const hasTeams = () => (user?.teams?.length ?? 0) > 0;
// Whether the user is a member of a specific team (or is Admin in "All BUs" mode)
const isTeamMember = (team) => {
if (!user) return false;
if (isInGroup('Admin') && adminScope === 'all') return true;
return (user.teams || []).includes(team);
};
// Toggle admin scope between 'my-teams' and 'all'
const toggleAdminScope = () => {
setAdminScope(prev => {
const next = prev === 'my-teams' ? 'all' : 'my-teams';
localStorage.setItem('admin_bu_scope', next);
return next;
});
};
// Returns the comma-joined teams string for API query params.
// Empty string means "no filter" (show all).
const getActiveTeamsParam = () => {
if (!user) return '';
if (isInGroup('Admin') && adminScope === 'all') return '';
const teams = user.teams || [];
return teams.join(',');
};
// Returns the list of teams available for UI selectors (compliance team picker, etc.)
// Admin in "All BUs" mode sees all known teams; otherwise scoped to user's teams.
const getAvailableTeams = () => {
if (!user) return [];
if (isInGroup('Admin') && adminScope === 'all') return KNOWN_TEAMS;
return user.teams || [];
};
const value = {
user,
loading,
error,
login,
logout,
checkAuth,
isInGroup,
canWrite,
canDelete,
canExport,
isAdmin,
isAuthenticated: !!user,
// Multi-BU tenancy
hasTeams,
isTeamMember,
adminScope,
toggleAdminScope,
getActiveTeamsParam,
getAvailableTeams,
KNOWN_TEAMS,
};
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}