Visual edit in Lovable

This commit is contained in:
gpt-engineer-app[bot]
2025-09-30 17:38:25 +00:00
parent 8aedee06c0
commit 82855249bb

View File

@@ -5,18 +5,11 @@ import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { supabase } from '@/integrations/supabase/client'; import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth'; import { useAuth } from '@/hooks/useAuth';
import { useUserRole } from '@/hooks/useUserRole'; import { useUserRole } from '@/hooks/useUserRole';
import { useToast } from '@/hooks/use-toast'; import { useToast } from '@/hooks/use-toast';
interface UserRole { interface UserRole {
id: string; id: string;
user_id: string; user_id: string;
@@ -27,7 +20,6 @@ interface UserRole {
display_name?: string; display_name?: string;
}; };
} }
export function UserRoleManager() { export function UserRoleManager() {
const [userRoles, setUserRoles] = useState<UserRole[]>([]); const [userRoles, setUserRoles] = useState<UserRole[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -36,111 +28,103 @@ export function UserRoleManager() {
const [newRole, setNewRole] = useState(''); const [newRole, setNewRole] = useState('');
const [searchResults, setSearchResults] = useState<any[]>([]); const [searchResults, setSearchResults] = useState<any[]>([]);
const [actionLoading, setActionLoading] = useState<string | null>(null); const [actionLoading, setActionLoading] = useState<string | null>(null);
const { user } = useAuth(); const {
const { isAdmin, isSuperuser, permissions } = useUserRole(); user
const { toast } = useToast(); } = useAuth();
const {
isAdmin,
isSuperuser,
permissions
} = useUserRole();
const {
toast
} = useToast();
const fetchUserRoles = async () => { const fetchUserRoles = async () => {
try { try {
const { data, error } = await supabase const {
.from('user_roles') data,
.select(` error
} = await supabase.from('user_roles').select(`
id, id,
user_id, user_id,
role, role,
granted_at granted_at
`) `).order('granted_at', {
.order('granted_at', { ascending: false }); ascending: false
});
if (error) throw error; if (error) throw error;
// Get unique user IDs // Get unique user IDs
const userIds = [...new Set((data || []).map(r => r.user_id))]; const userIds = [...new Set((data || []).map(r => r.user_id))];
// Fetch user profiles
const { data: profiles } = await supabase
.from('profiles')
.select('user_id, username, display_name')
.in('user_id', userIds);
// Fetch user profiles
const {
data: profiles
} = await supabase.from('profiles').select('user_id, username, display_name').in('user_id', userIds);
const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []); const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []);
// Combine data with profiles // Combine data with profiles
const userRolesWithProfiles = (data || []).map(role => ({ const userRolesWithProfiles = (data || []).map(role => ({
...role, ...role,
profiles: profileMap.get(role.user_id), profiles: profileMap.get(role.user_id)
})); }));
setUserRoles(userRolesWithProfiles); setUserRoles(userRolesWithProfiles);
} catch (error) { } catch (error) {
console.error('Error fetching user roles:', error); console.error('Error fetching user roles:', error);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to load user roles", description: "Failed to load user roles",
variant: "destructive", variant: "destructive"
}); });
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const searchUsers = async (search: string) => { const searchUsers = async (search: string) => {
if (!search.trim()) { if (!search.trim()) {
setSearchResults([]); setSearchResults([]);
return; return;
} }
try { try {
const { data, error } = await supabase const {
.from('profiles') data,
.select('user_id, username, display_name') error
.or(`username.ilike.%${search}%,display_name.ilike.%${search}%`) } = await supabase.from('profiles').select('user_id, username, display_name').or(`username.ilike.%${search}%,display_name.ilike.%${search}%`).limit(10);
.limit(10);
if (error) throw error; if (error) throw error;
// Filter out users who already have roles // Filter out users who already have roles
const existingUserIds = userRoles.map(ur => ur.user_id); const existingUserIds = userRoles.map(ur => ur.user_id);
const filteredResults = (data || []).filter( const filteredResults = (data || []).filter(profile => !existingUserIds.includes(profile.user_id));
profile => !existingUserIds.includes(profile.user_id)
);
setSearchResults(filteredResults); setSearchResults(filteredResults);
} catch (error) { } catch (error) {
console.error('Error searching users:', error); console.error('Error searching users:', error);
} }
}; };
useEffect(() => { useEffect(() => {
fetchUserRoles(); fetchUserRoles();
}, []); }, []);
useEffect(() => { useEffect(() => {
const debounceTimer = setTimeout(() => { const debounceTimer = setTimeout(() => {
searchUsers(newUserSearch); searchUsers(newUserSearch);
}, 300); }, 300);
return () => clearTimeout(debounceTimer); return () => clearTimeout(debounceTimer);
}, [newUserSearch, userRoles]); }, [newUserSearch, userRoles]);
const grantRole = async (userId: string, role: 'admin' | 'moderator' | 'user') => { const grantRole = async (userId: string, role: 'admin' | 'moderator' | 'user') => {
if (!isAdmin()) return; if (!isAdmin()) return;
setActionLoading('grant'); setActionLoading('grant');
try { try {
const { error } = await supabase.from('user_roles').insert([{ const {
error
} = await supabase.from('user_roles').insert([{
user_id: userId, user_id: userId,
role, role,
granted_by: user?.id, granted_by: user?.id
}]); }]);
if (error) throw error; if (error) throw error;
toast({ toast({
title: "Role Granted", title: "Role Granted",
description: `User has been granted ${role} role`, description: `User has been granted ${role} role`
}); });
setNewUserSearch(''); setNewUserSearch('');
setNewRole(''); setNewRole('');
setSearchResults([]); setSearchResults([]);
@@ -150,117 +134,77 @@ export function UserRoleManager() {
toast({ toast({
title: "Error", title: "Error",
description: "Failed to grant role", description: "Failed to grant role",
variant: "destructive", variant: "destructive"
}); });
} finally { } finally {
setActionLoading(null); setActionLoading(null);
} }
}; };
const revokeRole = async (roleId: string) => { const revokeRole = async (roleId: string) => {
if (!isAdmin()) return; if (!isAdmin()) return;
setActionLoading(roleId); setActionLoading(roleId);
try { try {
const { error } = await supabase const {
.from('user_roles') error
.delete() } = await supabase.from('user_roles').delete().eq('id', roleId);
.eq('id', roleId);
if (error) throw error; if (error) throw error;
toast({ toast({
title: "Role Revoked", title: "Role Revoked",
description: "User role has been revoked", description: "User role has been revoked"
}); });
fetchUserRoles(); fetchUserRoles();
} catch (error) { } catch (error) {
console.error('Error revoking role:', error); console.error('Error revoking role:', error);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to revoke role", description: "Failed to revoke role",
variant: "destructive", variant: "destructive"
}); });
} finally { } finally {
setActionLoading(null); setActionLoading(null);
} }
}; };
if (!isAdmin()) { if (!isAdmin()) {
return ( return <div className="text-center py-8">
<div className="text-center py-8">
<Shield className="w-12 h-12 text-muted-foreground mx-auto mb-4" /> <Shield className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-semibold mb-2">Access Denied</h3> <h3 className="text-lg font-semibold mb-2">Access Denied</h3>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
Only administrators can manage user roles. Only administrators can manage user roles.
</p> </p>
</div> </div>;
);
} }
if (loading) { if (loading) {
return ( return <div className="flex items-center justify-center p-8">
<div className="flex items-center justify-center p-8">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div> <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div> </div>;
);
} }
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()));
const filteredRoles = userRoles.filter(role => return <div className="space-y-6">
role.profiles?.username?.toLowerCase().includes(searchTerm.toLowerCase()) ||
role.profiles?.display_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
role.role.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div className="space-y-6">
{/* Add new role */} {/* Add new role */}
<Card> <Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<UserPlus className="w-5 h-5" />
Grant User Role
</CardTitle>
</CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div> <div>
<Label htmlFor="user-search">Search Users</Label> <Label htmlFor="user-search">Search Users</Label>
<div className="relative"> <div className="relative">
<Search className="absolute left-3 top-3 w-4 h-4 text-muted-foreground" /> <Search className="absolute left-3 top-3 w-4 h-4 text-muted-foreground" />
<Input <Input id="user-search" placeholder="Search by username or display name..." value={newUserSearch} onChange={e => setNewUserSearch(e.target.value)} className="pl-10" />
id="user-search"
placeholder="Search by username or display name..."
value={newUserSearch}
onChange={(e) => setNewUserSearch(e.target.value)}
className="pl-10"
/>
</div> </div>
{searchResults.length > 0 && ( {searchResults.length > 0 && <div className="mt-2 border rounded-lg bg-background">
<div className="mt-2 border rounded-lg bg-background"> {searchResults.map(profile => <div key={profile.user_id} className="p-3 hover:bg-muted/50 cursor-pointer border-b last:border-b-0" onClick={() => {
{searchResults.map((profile) => ( setNewUserSearch(profile.display_name || profile.username);
<div setSearchResults([profile]);
key={profile.user_id} }}>
className="p-3 hover:bg-muted/50 cursor-pointer border-b last:border-b-0"
onClick={() => {
setNewUserSearch(profile.display_name || profile.username);
setSearchResults([profile]);
}}
>
<div className="font-medium"> <div className="font-medium">
{profile.display_name || profile.username} {profile.display_name || profile.username}
</div> </div>
{profile.display_name && ( {profile.display_name && <div className="text-sm text-muted-foreground">
<div className="text-sm text-muted-foreground">
@{profile.username} @{profile.username}
</div> </div>}
)} </div>)}
</div> </div>}
))}
</div>
)}
</div> </div>
<div> <div>
@@ -271,30 +215,18 @@ export function UserRoleManager() {
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="moderator">Moderator</SelectItem> <SelectItem value="moderator">Moderator</SelectItem>
{isSuperuser() && ( {isSuperuser() && <SelectItem value="admin">Administrator</SelectItem>}
<SelectItem value="admin">Administrator</SelectItem>
)}
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
</div> </div>
<Button <Button onClick={() => {
onClick={() => { const selectedUser = searchResults.find(p => (p.display_name || p.username) === newUserSearch);
const selectedUser = searchResults.find( if (selectedUser && newRole) {
p => (p.display_name || p.username) === newUserSearch grantRole(selectedUser.user_id, newRole as 'admin' | 'moderator' | 'user');
); }
if (selectedUser && newRole) { }} disabled={!newRole || !searchResults.find(p => (p.display_name || p.username) === newUserSearch) || actionLoading === 'grant'} className="w-full md:w-auto">
grantRole(selectedUser.user_id, newRole as 'admin' | 'moderator' | 'user');
}
}}
disabled={
!newRole ||
!searchResults.find(p => (p.display_name || p.username) === newUserSearch) ||
actionLoading === 'grant'
}
className="w-full md:w-auto"
>
{actionLoading === 'grant' ? 'Granting...' : 'Grant Role'} {actionLoading === 'grant' ? 'Granting...' : 'Grant Role'}
</Button> </Button>
</CardContent> </CardContent>
@@ -305,40 +237,28 @@ export function UserRoleManager() {
<Label htmlFor="role-search">Search Existing Roles</Label> <Label htmlFor="role-search">Search Existing Roles</Label>
<div className="relative"> <div className="relative">
<Search className="absolute left-3 top-3 w-4 h-4 text-muted-foreground" /> <Search className="absolute left-3 top-3 w-4 h-4 text-muted-foreground" />
<Input <Input id="role-search" placeholder="Search users with roles..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} className="pl-10" />
id="role-search"
placeholder="Search users with roles..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div> </div>
</div> </div>
{/* User roles list */} {/* User roles list */}
<div className="space-y-3"> <div className="space-y-3">
{filteredRoles.length === 0 ? ( {filteredRoles.length === 0 ? <div className="text-center py-8">
<div className="text-center py-8">
<Shield className="w-12 h-12 text-muted-foreground mx-auto mb-4" /> <Shield className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
<h3 className="text-lg font-semibold mb-2">No roles found</h3> <h3 className="text-lg font-semibold mb-2">No roles found</h3>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
{searchTerm ? 'No users match your search criteria.' : 'No user roles have been granted yet.'} {searchTerm ? 'No users match your search criteria.' : 'No user roles have been granted yet.'}
</p> </p>
</div> </div> : filteredRoles.map(userRole => <Card key={userRole.id}>
) : (
filteredRoles.map((userRole) => (
<Card key={userRole.id}>
<CardContent className="flex items-center justify-between p-4"> <CardContent className="flex items-center justify-between p-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div> <div>
<div className="font-medium"> <div className="font-medium">
{userRole.profiles?.display_name || userRole.profiles?.username} {userRole.profiles?.display_name || userRole.profiles?.username}
</div> </div>
{userRole.profiles?.display_name && ( {userRole.profiles?.display_name && <div className="text-sm text-muted-foreground">
<div className="text-sm text-muted-foreground">
@{userRole.profiles.username} @{userRole.profiles.username}
</div> </div>}
)}
</div> </div>
<Badge variant={userRole.role === 'admin' ? 'default' : 'secondary'}> <Badge variant={userRole.role === 'admin' ? 'default' : 'secondary'}>
{userRole.role} {userRole.role}
@@ -346,21 +266,11 @@ export function UserRoleManager() {
</div> </div>
{/* Only show revoke button if current user can manage this role */} {/* Only show revoke button if current user can manage this role */}
{(isSuperuser() || (isAdmin() && !['admin', 'superuser'].includes(userRole.role))) && ( {(isSuperuser() || isAdmin() && !['admin', 'superuser'].includes(userRole.role)) && <Button variant="outline" size="sm" onClick={() => revokeRole(userRole.id)} disabled={actionLoading === userRole.id}>
<Button
variant="outline"
size="sm"
onClick={() => revokeRole(userRole.id)}
disabled={actionLoading === userRole.id}
>
<X className="w-4 h-4" /> <X className="w-4 h-4" />
</Button> </Button>}
)}
</CardContent> </CardContent>
</Card> </Card>)}
))
)}
</div> </div>
</div> </div>;
);
} }