import { useState, useEffect } from 'react'; import { Shield, UserPlus, X, Search } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { supabase } from '@/lib/supabaseClient'; import { useAuth } from '@/hooks/useAuth'; import { useUserRole } from '@/hooks/useUserRole'; import { handleError, handleNonCriticalError, handleSuccess, getErrorMessage } from '@/lib/errorHandler'; // Type-safe role definitions const VALID_ROLES = ['admin', 'moderator', 'user'] as const; type ValidRole = typeof VALID_ROLES[number]; /** * Type guard to validate role strings * Prevents unsafe casting and ensures type safety */ function isValidRole(role: string): role is ValidRole { return VALID_ROLES.includes(role as ValidRole); } /** * Get display label for a role */ function getRoleLabel(role: string): string { const labels: Record = { admin: 'Administrator', moderator: 'Moderator', user: 'User', }; return isValidRole(role) ? labels[role] : role; } interface ProfileSearchResult { user_id: string; username: string; display_name?: string; } interface UserRole { id: string; user_id: string; role: string; granted_at: string; profiles?: { username: string; display_name?: string; }; } export function UserRoleManager() { const [userRoles, setUserRoles] = useState([]); const [loading, setLoading] = useState(true); const [searchTerm, setSearchTerm] = useState(''); const [newUserSearch, setNewUserSearch] = useState(''); const [newRole, setNewRole] = useState(''); const [searchResults, setSearchResults] = useState([]); const [actionLoading, setActionLoading] = useState(null); const { user } = useAuth(); const { isAdmin, isSuperuser, permissions } = useUserRole(); const fetchUserRoles = async () => { try { const { data, error } = await supabase.from('user_roles').select(` id, user_id, role, granted_at `).order('granted_at', { ascending: false }); if (error) throw error; // Get unique user IDs const userIds = [...new Set((data || []).map(r => r.user_id))]; // Fetch user profiles with emails (for admins) let profiles: Array<{ user_id: string; username: string; display_name?: string }> | null = null; const { data: allProfiles, error: rpcError } = await supabase .rpc('get_users_with_emails'); if (rpcError) { // Fall back to basic profiles const { data: basicProfiles } = await supabase .from('profiles') .select('user_id, username, display_name') .in('user_id', userIds); profiles = basicProfiles as typeof profiles; } else { profiles = allProfiles?.filter(p => userIds.includes(p.user_id)) || null; } const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []); // Combine data with profiles const userRolesWithProfiles = (data || []).map(role => ({ ...role, profiles: profileMap.get(role.user_id) })); setUserRoles(userRolesWithProfiles); } catch (error: unknown) { handleError(error, { action: 'Load User Roles', userId: user?.id }); } finally { setLoading(false); } }; const searchUsers = async (search: string) => { if (!search.trim()) { setSearchResults([]); return; } try { let data; const { data: allUsers, error: rpcError } = await supabase .rpc('get_users_with_emails'); if (rpcError) { // Fall back to basic profiles const { data: basicProfiles, error: profilesError } = await supabase .from('profiles') .select('user_id, username, display_name') .ilike('username', `%${search}%`); if (profilesError) throw profilesError; data = basicProfiles?.slice(0, 10); } else { // Filter by search term data = allUsers?.filter(user => user.username.toLowerCase().includes(search.toLowerCase()) || user.display_name?.toLowerCase().includes(search.toLowerCase()) ).slice(0, 10); } // Filter out users who already have roles const existingUserIds = userRoles.map(ur => ur.user_id); const filteredResults = (data || []).filter(profile => !existingUserIds.includes(profile.user_id)); setSearchResults(filteredResults); } catch (error: unknown) { handleNonCriticalError(error, { action: 'Search Users', userId: user?.id, metadata: { search } }); } }; useEffect(() => { fetchUserRoles(); }, []); useEffect(() => { const debounceTimer = setTimeout(() => { searchUsers(newUserSearch); }, 300); return () => clearTimeout(debounceTimer); }, [newUserSearch, userRoles]); const grantRole = async (userId: string, role: ValidRole) => { if (!isAdmin()) return; // Double-check role validity before database operation if (!isValidRole(role)) { handleError(new Error('Invalid role'), { action: 'Grant Role', userId: user?.id, metadata: { targetUserId: userId, attemptedRole: role } }); return; } setActionLoading('grant'); try { const { error } = await supabase.from('user_roles').insert([{ user_id: userId, role, granted_by: user?.id }]); if (error) throw error; handleSuccess('Role Granted', `User has been granted ${getRoleLabel(role)} role`); setNewUserSearch(''); setNewRole(''); setSearchResults([]); fetchUserRoles(); } catch (error: unknown) { handleError(error, { action: 'Grant Role', userId: user?.id, metadata: { targetUserId: userId, role } }); } finally { setActionLoading(null); } }; const revokeRole = async (roleId: string) => { if (!isAdmin()) return; setActionLoading(roleId); try { const { error } = await supabase.from('user_roles').delete().eq('id', roleId); if (error) throw error; handleSuccess('Role Revoked', 'User role has been revoked'); fetchUserRoles(); } catch (error: unknown) { handleError(error, { action: 'Revoke Role', userId: user?.id, metadata: { roleId } }); } finally { setActionLoading(null); } }; if (!isAdmin()) { return

Access Denied

Only administrators can manage user roles.

; } if (loading) { return
; } const filteredRoles = userRoles.filter(role => role.profiles?.username?.toLowerCase().includes(searchTerm.toLowerCase()) || role.profiles?.display_name?.toLowerCase().includes(searchTerm.toLowerCase()) || role.role.toLowerCase().includes(searchTerm.toLowerCase())); return
{/* Add new role */}
setNewUserSearch(e.target.value)} className="pl-10" />
{searchResults.length > 0 &&
{searchResults.map(profile =>
{ setNewUserSearch(profile.display_name || profile.username); setSearchResults([profile]); }}>
{profile.display_name || profile.username}
{profile.display_name &&
@{profile.username}
}
)}
}
{/* Search existing roles */}
setSearchTerm(e.target.value)} className="pl-10" />
{/* User roles list */}
{filteredRoles.length === 0 ?

No roles found

{searchTerm ? 'No users match your search criteria.' : 'No user roles have been granted yet.'}

: filteredRoles.map(userRole =>
{userRole.profiles?.display_name || userRole.profiles?.username}
{userRole.profiles?.display_name &&
@{userRole.profiles.username}
}
{userRole.role}
{/* Only show revoke button if current user can manage this role */} {(isSuperuser() || isAdmin() && !['admin', 'superuser'].includes(userRole.role)) && }
)}
; }