mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 08:11:13 -05:00
Add moderation queue tables
This commit is contained in:
@@ -20,6 +20,8 @@ import SubmissionGuidelines from "./pages/SubmissionGuidelines";
|
|||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
|
import Admin from "./pages/Admin";
|
||||||
|
|
||||||
const App = () => (
|
const App = () => (
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
@@ -39,6 +41,7 @@ const App = () => (
|
|||||||
<Route path="/auth" element={<Auth />} />
|
<Route path="/auth" element={<Auth />} />
|
||||||
<Route path="/profile" element={<Profile />} />
|
<Route path="/profile" element={<Profile />} />
|
||||||
<Route path="/profile/:username" element={<Profile />} />
|
<Route path="/profile/:username" element={<Profile />} />
|
||||||
|
<Route path="/admin" element={<Admin />} />
|
||||||
<Route path="/terms" element={<Terms />} />
|
<Route path="/terms" element={<Terms />} />
|
||||||
<Route path="/privacy" element={<Privacy />} />
|
<Route path="/privacy" element={<Privacy />} />
|
||||||
<Route path="/submission-guidelines" element={<SubmissionGuidelines />} />
|
<Route path="/submission-guidelines" element={<SubmissionGuidelines />} />
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { Search, Menu, Zap, MapPin, Star, ChevronDown, Building, Users, Crown, Palette } from 'lucide-react';
|
import { Search, Menu, Zap, MapPin, Star, ChevronDown, Building, Users, Crown, Palette, Shield } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||||
@@ -9,8 +9,11 @@ import { Link, useNavigate } from 'react-router-dom';
|
|||||||
import { SearchDropdown } from '@/components/search/SearchDropdown';
|
import { SearchDropdown } from '@/components/search/SearchDropdown';
|
||||||
import { AuthButtons } from '@/components/auth/AuthButtons';
|
import { AuthButtons } from '@/components/auth/AuthButtons';
|
||||||
import { ThemeToggle } from '@/components/theme/ThemeToggle';
|
import { ThemeToggle } from '@/components/theme/ThemeToggle';
|
||||||
|
import { useUserRole } from '@/hooks/useUserRole';
|
||||||
|
|
||||||
export function Header() {
|
export function Header() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { isModerator } = useUserRole();
|
||||||
return <header className="sticky top-0 z-50 w-full border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
return <header className="sticky top-0 z-50 w-full border-b border-border bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||||
<div className="container flex h-16 items-center justify-between px-4">
|
<div className="container flex h-16 items-center justify-between px-4">
|
||||||
{/* Logo and Brand */}
|
{/* Logo and Brand */}
|
||||||
@@ -67,6 +70,14 @@ export function Header() {
|
|||||||
|
|
||||||
{/* User Actions */}
|
{/* User Actions */}
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
{isModerator() && (
|
||||||
|
<Button variant="ghost" size="sm" asChild>
|
||||||
|
<Link to="/admin" className="flex items-center gap-2">
|
||||||
|
<Shield className="w-4 h-4" />
|
||||||
|
Admin
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
<AuthButtons />
|
<AuthButtons />
|
||||||
|
|
||||||
|
|||||||
291
src/components/moderation/ModerationQueue.tsx
Normal file
291
src/components/moderation/ModerationQueue.tsx
Normal file
@@ -0,0 +1,291 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { CheckCircle, XCircle, Eye, Calendar, User } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { useToast } from '@/hooks/use-toast';
|
||||||
|
import { format } from 'date-fns';
|
||||||
|
|
||||||
|
interface ModerationItem {
|
||||||
|
id: string;
|
||||||
|
type: 'review' | 'content_submission';
|
||||||
|
content: any;
|
||||||
|
created_at: string;
|
||||||
|
user_id: string;
|
||||||
|
status: string;
|
||||||
|
user_profile?: {
|
||||||
|
username: string;
|
||||||
|
display_name?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ModerationQueue() {
|
||||||
|
const [items, setItems] = useState<ModerationItem[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [actionLoading, setActionLoading] = useState<string | null>(null);
|
||||||
|
const [notes, setNotes] = useState<Record<string, string>>({});
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
const fetchItems = async () => {
|
||||||
|
try {
|
||||||
|
// Fetch pending reviews with profile data
|
||||||
|
const { data: reviews, error: reviewsError } = await supabase
|
||||||
|
.from('reviews')
|
||||||
|
.select(`
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
content,
|
||||||
|
rating,
|
||||||
|
created_at,
|
||||||
|
user_id,
|
||||||
|
moderation_status
|
||||||
|
`)
|
||||||
|
.in('moderation_status', ['pending', 'flagged'])
|
||||||
|
.order('created_at', { ascending: true });
|
||||||
|
|
||||||
|
if (reviewsError) throw reviewsError;
|
||||||
|
|
||||||
|
// Fetch pending content submissions
|
||||||
|
const { data: submissions, error: submissionsError } = await supabase
|
||||||
|
.from('content_submissions')
|
||||||
|
.select(`
|
||||||
|
id,
|
||||||
|
content,
|
||||||
|
submission_type,
|
||||||
|
created_at,
|
||||||
|
user_id,
|
||||||
|
status
|
||||||
|
`)
|
||||||
|
.eq('status', 'pending')
|
||||||
|
.order('created_at', { ascending: true });
|
||||||
|
|
||||||
|
if (submissionsError) throw submissionsError;
|
||||||
|
|
||||||
|
// Get unique user IDs to fetch profiles
|
||||||
|
const userIds = [
|
||||||
|
...(reviews || []).map(r => r.user_id),
|
||||||
|
...(submissions || []).map(s => s.user_id)
|
||||||
|
];
|
||||||
|
|
||||||
|
// Fetch profiles for all users
|
||||||
|
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]) || []);
|
||||||
|
|
||||||
|
// Combine and format items
|
||||||
|
const formattedItems: ModerationItem[] = [
|
||||||
|
...(reviews || []).map(review => ({
|
||||||
|
id: review.id,
|
||||||
|
type: 'review' as const,
|
||||||
|
content: review,
|
||||||
|
created_at: review.created_at,
|
||||||
|
user_id: review.user_id,
|
||||||
|
status: review.moderation_status,
|
||||||
|
user_profile: profileMap.get(review.user_id),
|
||||||
|
})),
|
||||||
|
...(submissions || []).map(submission => ({
|
||||||
|
id: submission.id,
|
||||||
|
type: 'content_submission' as const,
|
||||||
|
content: submission,
|
||||||
|
created_at: submission.created_at,
|
||||||
|
user_id: submission.user_id,
|
||||||
|
status: submission.status,
|
||||||
|
user_profile: profileMap.get(submission.user_id),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Sort by creation date
|
||||||
|
formattedItems.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
|
||||||
|
|
||||||
|
setItems(formattedItems);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching moderation items:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: "Failed to load moderation queue",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchItems();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleModerationAction = async (
|
||||||
|
item: ModerationItem,
|
||||||
|
action: 'approved' | 'rejected',
|
||||||
|
moderatorNotes?: string
|
||||||
|
) => {
|
||||||
|
setActionLoading(item.id);
|
||||||
|
try {
|
||||||
|
const table = item.type === 'review' ? 'reviews' : 'content_submissions';
|
||||||
|
const statusField = item.type === 'review' ? 'moderation_status' : 'status';
|
||||||
|
|
||||||
|
const updateData: any = {
|
||||||
|
[statusField]: action,
|
||||||
|
[`moderated_at`]: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (moderatorNotes) {
|
||||||
|
updateData.reviewer_notes = moderatorNotes;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { error } = await supabase
|
||||||
|
.from(table)
|
||||||
|
.update(updateData)
|
||||||
|
.eq('id', item.id);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: `Content ${action}`,
|
||||||
|
description: `The ${item.type} has been ${action}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove item from queue
|
||||||
|
setItems(prev => prev.filter(i => i.id !== item.id));
|
||||||
|
|
||||||
|
// Clear notes
|
||||||
|
setNotes(prev => {
|
||||||
|
const newNotes = { ...prev };
|
||||||
|
delete newNotes[item.id];
|
||||||
|
return newNotes;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error moderating content:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: `Failed to ${action} content`,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setActionLoading(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (items.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<CheckCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-semibold mb-2">Queue is empty</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
No pending items require moderation at this time.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{items.map((item) => (
|
||||||
|
<Card key={item.id} className="border-l-4 border-l-amber-500">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Badge variant={item.status === 'flagged' ? 'destructive' : 'secondary'}>
|
||||||
|
{item.type === 'review' ? 'Review' : 'Submission'}
|
||||||
|
</Badge>
|
||||||
|
{item.status === 'flagged' && (
|
||||||
|
<Badge variant="destructive">Flagged</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<Calendar className="w-4 h-4" />
|
||||||
|
{format(new Date(item.created_at), 'MMM d, yyyy HH:mm')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{item.user_profile && (
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<User className="w-4 h-4 text-muted-foreground" />
|
||||||
|
<span className="font-medium">
|
||||||
|
{item.user_profile.display_name || item.user_profile.username}
|
||||||
|
</span>
|
||||||
|
{item.user_profile.display_name && (
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
@{item.user_profile.username}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="bg-muted/50 p-4 rounded-lg">
|
||||||
|
{item.type === 'review' ? (
|
||||||
|
<div>
|
||||||
|
{item.content.title && (
|
||||||
|
<h4 className="font-semibold mb-2">{item.content.title}</h4>
|
||||||
|
)}
|
||||||
|
{item.content.content && (
|
||||||
|
<p className="text-sm mb-2">{item.content.content}</p>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<span>Rating: {item.content.rating}/5</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-muted-foreground mb-2">
|
||||||
|
Type: {item.content.submission_type}
|
||||||
|
</div>
|
||||||
|
<pre className="text-sm whitespace-pre-wrap">
|
||||||
|
{JSON.stringify(item.content.content, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor={`notes-${item.id}`}>Moderation Notes (optional)</Label>
|
||||||
|
<Textarea
|
||||||
|
id={`notes-${item.id}`}
|
||||||
|
placeholder="Add notes about your moderation decision..."
|
||||||
|
value={notes[item.id] || ''}
|
||||||
|
onChange={(e) => setNotes(prev => ({ ...prev, [item.id]: e.target.value }))}
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-2 pt-2">
|
||||||
|
<Button
|
||||||
|
onClick={() => handleModerationAction(item, 'approved', notes[item.id])}
|
||||||
|
disabled={actionLoading === item.id}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
<CheckCircle className="w-4 h-4 mr-2" />
|
||||||
|
Approve
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => handleModerationAction(item, 'rejected', notes[item.id])}
|
||||||
|
disabled={actionLoading === item.id}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
<XCircle className="w-4 h-4 mr-2" />
|
||||||
|
Reject
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
148
src/components/moderation/ReportButton.tsx
Normal file
148
src/components/moderation/ReportButton.tsx
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Flag, AlertTriangle } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
|
import { useToast } from '@/hooks/use-toast';
|
||||||
|
|
||||||
|
interface ReportButtonProps {
|
||||||
|
entityType: 'review' | 'profile' | 'content_submission';
|
||||||
|
entityId: string;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const REPORT_TYPES = [
|
||||||
|
{ value: 'spam', label: 'Spam' },
|
||||||
|
{ value: 'inappropriate', label: 'Inappropriate Content' },
|
||||||
|
{ value: 'harassment', label: 'Harassment' },
|
||||||
|
{ value: 'fake_info', label: 'Fake Information' },
|
||||||
|
{ value: 'offensive', label: 'Offensive Language' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function ReportButton({ entityType, entityId, className }: ReportButtonProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [reportType, setReportType] = useState('');
|
||||||
|
const [reason, setReason] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!user || !reportType) return;
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const { error } = await supabase.from('reports').insert({
|
||||||
|
reporter_id: user.id,
|
||||||
|
reported_entity_type: entityType,
|
||||||
|
reported_entity_id: entityId,
|
||||||
|
report_type: reportType,
|
||||||
|
reason: reason.trim() || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Report Submitted",
|
||||||
|
description: "Thank you for your report. We'll review it shortly.",
|
||||||
|
});
|
||||||
|
|
||||||
|
setOpen(false);
|
||||||
|
setReportType('');
|
||||||
|
setReason('');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error submitting report:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: "Failed to submit report. Please try again.",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button variant="ghost" size="sm" className={className}>
|
||||||
|
<Flag className="w-4 h-4 mr-2" />
|
||||||
|
Report
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<AlertTriangle className="w-5 h-5 text-destructive" />
|
||||||
|
Report Content
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Help us maintain a safe community by reporting inappropriate content.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="report-type">Reason for report</Label>
|
||||||
|
<Select value={reportType} onValueChange={setReportType}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select a reason" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{REPORT_TYPES.map((type) => (
|
||||||
|
<SelectItem key={type.value} value={type.value}>
|
||||||
|
{type.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="reason">Additional details (optional)</Label>
|
||||||
|
<Textarea
|
||||||
|
id="reason"
|
||||||
|
placeholder="Provide additional context about your report..."
|
||||||
|
value={reason}
|
||||||
|
onChange={(e) => setReason(e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => setOpen(false)}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={!reportType || loading}
|
||||||
|
variant="destructive"
|
||||||
|
>
|
||||||
|
{loading ? 'Submitting...' : 'Submit Report'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
261
src/components/moderation/ReportsQueue.tsx
Normal file
261
src/components/moderation/ReportsQueue.tsx
Normal file
@@ -0,0 +1,261 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { CheckCircle, XCircle, ExternalLink, Calendar, User, Flag } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Card, CardContent, CardHeader } from '@/components/ui/card';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { useToast } from '@/hooks/use-toast';
|
||||||
|
import { format } from 'date-fns';
|
||||||
|
|
||||||
|
interface Report {
|
||||||
|
id: string;
|
||||||
|
reported_entity_type: string;
|
||||||
|
reported_entity_id: string;
|
||||||
|
report_type: string;
|
||||||
|
reason: string;
|
||||||
|
status: string;
|
||||||
|
created_at: string;
|
||||||
|
reporter_profile?: {
|
||||||
|
username: string;
|
||||||
|
display_name?: string;
|
||||||
|
};
|
||||||
|
reported_content?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
const REPORT_TYPE_LABELS = {
|
||||||
|
spam: 'Spam',
|
||||||
|
inappropriate: 'Inappropriate Content',
|
||||||
|
harassment: 'Harassment',
|
||||||
|
fake_info: 'Fake Information',
|
||||||
|
offensive: 'Offensive Language',
|
||||||
|
};
|
||||||
|
|
||||||
|
const STATUS_COLORS = {
|
||||||
|
pending: 'secondary',
|
||||||
|
reviewed: 'default',
|
||||||
|
dismissed: 'outline',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function ReportsQueue() {
|
||||||
|
const [reports, setReports] = useState<Report[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [actionLoading, setActionLoading] = useState<string | null>(null);
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
const fetchReports = async () => {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('reports')
|
||||||
|
.select(`
|
||||||
|
id,
|
||||||
|
reported_entity_type,
|
||||||
|
reported_entity_id,
|
||||||
|
report_type,
|
||||||
|
reason,
|
||||||
|
status,
|
||||||
|
created_at,
|
||||||
|
reporter_id
|
||||||
|
`)
|
||||||
|
.eq('status', 'pending')
|
||||||
|
.order('created_at', { ascending: true });
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
// Get unique reporter IDs
|
||||||
|
const reporterIds = [...new Set((data || []).map(r => r.reporter_id))];
|
||||||
|
|
||||||
|
// Fetch reporter profiles
|
||||||
|
const { data: profiles } = await supabase
|
||||||
|
.from('profiles')
|
||||||
|
.select('user_id, username, display_name')
|
||||||
|
.in('user_id', reporterIds);
|
||||||
|
|
||||||
|
const profileMap = new Map(profiles?.map(p => [p.user_id, p]) || []);
|
||||||
|
|
||||||
|
// Fetch the reported content for each report
|
||||||
|
const reportsWithContent = await Promise.all(
|
||||||
|
(data || []).map(async (report) => {
|
||||||
|
let reportedContent = null;
|
||||||
|
|
||||||
|
if (report.reported_entity_type === 'review') {
|
||||||
|
const { data: reviewData } = await supabase
|
||||||
|
.from('reviews')
|
||||||
|
.select('title, content, rating')
|
||||||
|
.eq('id', report.reported_entity_id)
|
||||||
|
.single();
|
||||||
|
reportedContent = reviewData;
|
||||||
|
}
|
||||||
|
// Add other entity types as needed
|
||||||
|
|
||||||
|
return {
|
||||||
|
...report,
|
||||||
|
reporter_profile: profileMap.get(report.reporter_id),
|
||||||
|
reported_content: reportedContent,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
setReports(reportsWithContent);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching reports:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: "Failed to load reports queue",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchReports();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleReportAction = async (reportId: string, action: 'reviewed' | 'dismissed') => {
|
||||||
|
setActionLoading(reportId);
|
||||||
|
try {
|
||||||
|
const { error } = await supabase
|
||||||
|
.from('reports')
|
||||||
|
.update({
|
||||||
|
status: action,
|
||||||
|
reviewed_at: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.eq('id', reportId);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: `Report ${action}`,
|
||||||
|
description: `The report has been marked as ${action}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remove report from queue
|
||||||
|
setReports(prev => prev.filter(r => r.id !== reportId));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating report:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: `Failed to ${action} report`,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setActionLoading(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reports.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<CheckCircle className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-semibold mb-2">No pending reports</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
All user reports have been reviewed.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{reports.map((report) => (
|
||||||
|
<Card key={report.id} className="border-l-4 border-l-red-500">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Badge variant="destructive">
|
||||||
|
<Flag className="w-3 h-3 mr-1" />
|
||||||
|
{REPORT_TYPE_LABELS[report.report_type as keyof typeof REPORT_TYPE_LABELS]}
|
||||||
|
</Badge>
|
||||||
|
<Badge variant="outline">
|
||||||
|
{report.reported_entity_type}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||||
|
<Calendar className="w-4 h-4" />
|
||||||
|
{format(new Date(report.created_at), 'MMM d, yyyy HH:mm')}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{report.reporter_profile && (
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<User className="w-4 h-4 text-muted-foreground" />
|
||||||
|
<span>Reported by:</span>
|
||||||
|
<span className="font-medium">
|
||||||
|
{report.reporter_profile.display_name || report.reporter_profile.username}
|
||||||
|
</span>
|
||||||
|
{report.reporter_profile.display_name && (
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
@{report.reporter_profile.username}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{report.reason && (
|
||||||
|
<div>
|
||||||
|
<Label>Report Reason:</Label>
|
||||||
|
<p className="text-sm bg-muted/50 p-3 rounded-lg mt-1">
|
||||||
|
{report.reason}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{report.reported_content && (
|
||||||
|
<div>
|
||||||
|
<Label>Reported Content:</Label>
|
||||||
|
<div className="bg-destructive/5 border border-destructive/20 p-4 rounded-lg mt-1">
|
||||||
|
{report.reported_entity_type === 'review' && (
|
||||||
|
<div>
|
||||||
|
{report.reported_content.title && (
|
||||||
|
<h4 className="font-semibold mb-2">{report.reported_content.title}</h4>
|
||||||
|
)}
|
||||||
|
{report.reported_content.content && (
|
||||||
|
<p className="text-sm mb-2">{report.reported_content.content}</p>
|
||||||
|
)}
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
Rating: {report.reported_content.rating}/5
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex gap-2 pt-2">
|
||||||
|
<Button
|
||||||
|
onClick={() => handleReportAction(report.id, 'reviewed')}
|
||||||
|
disabled={actionLoading === report.id}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
<CheckCircle className="w-4 h-4 mr-2" />
|
||||||
|
Mark Reviewed
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => handleReportAction(report.id, 'dismissed')}
|
||||||
|
disabled={actionLoading === report.id}
|
||||||
|
className="flex-1"
|
||||||
|
>
|
||||||
|
<XCircle className="w-4 h-4 mr-2" />
|
||||||
|
Dismiss
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
361
src/components/moderation/UserRoleManager.tsx
Normal file
361
src/components/moderation/UserRoleManager.tsx
Normal file
@@ -0,0 +1,361 @@
|
|||||||
|
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 '@/integrations/supabase/client';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
|
import { useUserRole } from '@/hooks/useUserRole';
|
||||||
|
import { useToast } from '@/hooks/use-toast';
|
||||||
|
|
||||||
|
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<UserRole[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
|
const [newUserSearch, setNewUserSearch] = useState('');
|
||||||
|
const [newRole, setNewRole] = useState('');
|
||||||
|
const [searchResults, setSearchResults] = useState<any[]>([]);
|
||||||
|
const [actionLoading, setActionLoading] = useState<string | null>(null);
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { isAdmin } = useUserRole();
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
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
|
||||||
|
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]) || []);
|
||||||
|
|
||||||
|
// Combine data with profiles
|
||||||
|
const userRolesWithProfiles = (data || []).map(role => ({
|
||||||
|
...role,
|
||||||
|
profiles: profileMap.get(role.user_id),
|
||||||
|
}));
|
||||||
|
|
||||||
|
setUserRoles(userRolesWithProfiles);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching user roles:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: "Failed to load user roles",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const searchUsers = async (search: string) => {
|
||||||
|
if (!search.trim()) {
|
||||||
|
setSearchResults([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('profiles')
|
||||||
|
.select('user_id, username, display_name')
|
||||||
|
.or(`username.ilike.%${search}%,display_name.ilike.%${search}%`)
|
||||||
|
.limit(10);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
console.error('Error searching users:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchUserRoles();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const debounceTimer = setTimeout(() => {
|
||||||
|
searchUsers(newUserSearch);
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
return () => clearTimeout(debounceTimer);
|
||||||
|
}, [newUserSearch, userRoles]);
|
||||||
|
|
||||||
|
const grantRole = async (userId: string, role: 'admin' | 'moderator' | 'user') => {
|
||||||
|
if (!isAdmin()) return;
|
||||||
|
|
||||||
|
setActionLoading('grant');
|
||||||
|
try {
|
||||||
|
const { error } = await supabase.from('user_roles').insert([{
|
||||||
|
user_id: userId,
|
||||||
|
role,
|
||||||
|
granted_by: user?.id,
|
||||||
|
}]);
|
||||||
|
|
||||||
|
if (error) throw error;
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Role Granted",
|
||||||
|
description: `User has been granted ${role} role`,
|
||||||
|
});
|
||||||
|
|
||||||
|
setNewUserSearch('');
|
||||||
|
setNewRole('');
|
||||||
|
setSearchResults([]);
|
||||||
|
fetchUserRoles();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error granting role:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: "Failed to grant role",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} 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;
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Role Revoked",
|
||||||
|
description: "User role has been revoked",
|
||||||
|
});
|
||||||
|
|
||||||
|
fetchUserRoles();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error revoking role:', error);
|
||||||
|
toast({
|
||||||
|
title: "Error",
|
||||||
|
description: "Failed to revoke role",
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setActionLoading(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isAdmin()) {
|
||||||
|
return (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<Shield className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
|
||||||
|
<h3 className="text-lg font-semibold mb-2">Access Denied</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Only administrators can manage user roles.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Add new role */}
|
||||||
|
<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">
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="user-search">Search Users</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-3 w-4 h-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
id="user-search"
|
||||||
|
placeholder="Search by username or display name..."
|
||||||
|
value={newUserSearch}
|
||||||
|
onChange={(e) => setNewUserSearch(e.target.value)}
|
||||||
|
className="pl-10"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{searchResults.length > 0 && (
|
||||||
|
<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={() => {
|
||||||
|
setNewUserSearch(profile.display_name || profile.username);
|
||||||
|
setSearchResults([profile]);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="font-medium">
|
||||||
|
{profile.display_name || profile.username}
|
||||||
|
</div>
|
||||||
|
{profile.display_name && (
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
@{profile.username}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="role-select">Role</Label>
|
||||||
|
<Select value={newRole} onValueChange={setNewRole}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Select a role" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="moderator">Moderator</SelectItem>
|
||||||
|
<SelectItem value="admin">Administrator</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
const selectedUser = searchResults.find(
|
||||||
|
p => (p.display_name || p.username) === newUserSearch
|
||||||
|
);
|
||||||
|
if (selectedUser && newRole) {
|
||||||
|
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'}
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Search existing roles */}
|
||||||
|
<div>
|
||||||
|
<Label htmlFor="role-search">Search Existing Roles</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-3 w-4 h-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
id="role-search"
|
||||||
|
placeholder="Search users with roles..."
|
||||||
|
value={searchTerm}
|
||||||
|
onChange={(e) => setSearchTerm(e.target.value)}
|
||||||
|
className="pl-10"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* User roles list */}
|
||||||
|
<div className="space-y-3">
|
||||||
|
{filteredRoles.length === 0 ? (
|
||||||
|
<div className="text-center py-8">
|
||||||
|
<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>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
{searchTerm ? 'No users match your search criteria.' : 'No user roles have been granted yet.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
filteredRoles.map((userRole) => (
|
||||||
|
<Card key={userRole.id}>
|
||||||
|
<CardContent className="flex items-center justify-between p-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="font-medium">
|
||||||
|
{userRole.profiles?.display_name || userRole.profiles?.username}
|
||||||
|
</div>
|
||||||
|
{userRole.profiles?.display_name && (
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
@{userRole.profiles.username}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Badge variant={userRole.role === 'admin' ? 'default' : 'secondary'}>
|
||||||
|
{userRole.role}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => revokeRole(userRole.id)}
|
||||||
|
disabled={actionLoading === userRole.id}
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4" />
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { Badge } from '@/components/ui/badge';
|
|||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
import { Star, ThumbsUp, Calendar, MapPin } from 'lucide-react';
|
import { Star, ThumbsUp, Calendar, MapPin } from 'lucide-react';
|
||||||
import { supabase } from '@/integrations/supabase/client';
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { ReportButton } from '@/components/moderation/ReportButton';
|
||||||
|
|
||||||
interface ReviewWithProfile {
|
interface ReviewWithProfile {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -185,6 +186,12 @@ export function ReviewsList({ entityType, entityId, entityName }: ReviewsListPro
|
|||||||
<ThumbsUp className="w-3 h-3" />
|
<ThumbsUp className="w-3 h-3" />
|
||||||
<span>{review.helpful_votes} helpful</span>
|
<span>{review.helpful_votes} helpful</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<ReportButton
|
||||||
|
entityType="review"
|
||||||
|
entityId={review.id}
|
||||||
|
className="text-xs"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
54
src/hooks/useUserRole.ts
Normal file
54
src/hooks/useUserRole.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
|
|
||||||
|
export type UserRole = 'admin' | 'moderator' | 'user';
|
||||||
|
|
||||||
|
export function useUserRole() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [roles, setRoles] = useState<UserRole[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user) {
|
||||||
|
setRoles([]);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchRoles = async () => {
|
||||||
|
try {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from('user_roles')
|
||||||
|
.select('role')
|
||||||
|
.eq('user_id', user.id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error('Error fetching user roles:', error);
|
||||||
|
setRoles([]);
|
||||||
|
} else {
|
||||||
|
setRoles(data?.map(r => r.role as UserRole) || []);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching user roles:', error);
|
||||||
|
setRoles([]);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchRoles();
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
const hasRole = (role: UserRole) => roles.includes(role);
|
||||||
|
const isModerator = () => hasRole('admin') || hasRole('moderator');
|
||||||
|
const isAdmin = () => hasRole('admin');
|
||||||
|
|
||||||
|
return {
|
||||||
|
roles,
|
||||||
|
loading,
|
||||||
|
hasRole,
|
||||||
|
isModerator,
|
||||||
|
isAdmin
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -355,6 +355,48 @@ export type Database = {
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
reports: {
|
||||||
|
Row: {
|
||||||
|
created_at: string
|
||||||
|
id: string
|
||||||
|
reason: string | null
|
||||||
|
report_type: string
|
||||||
|
reported_entity_id: string
|
||||||
|
reported_entity_type: string
|
||||||
|
reporter_id: string
|
||||||
|
reviewed_at: string | null
|
||||||
|
reviewed_by: string | null
|
||||||
|
status: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
created_at?: string
|
||||||
|
id?: string
|
||||||
|
reason?: string | null
|
||||||
|
report_type: string
|
||||||
|
reported_entity_id: string
|
||||||
|
reported_entity_type: string
|
||||||
|
reporter_id: string
|
||||||
|
reviewed_at?: string | null
|
||||||
|
reviewed_by?: string | null
|
||||||
|
status?: string
|
||||||
|
updated_at?: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
created_at?: string
|
||||||
|
id?: string
|
||||||
|
reason?: string | null
|
||||||
|
report_type?: string
|
||||||
|
reported_entity_id?: string
|
||||||
|
reported_entity_type?: string
|
||||||
|
reporter_id?: string
|
||||||
|
reviewed_at?: string | null
|
||||||
|
reviewed_by?: string | null
|
||||||
|
status?: string
|
||||||
|
updated_at?: string
|
||||||
|
}
|
||||||
|
Relationships: []
|
||||||
|
}
|
||||||
reviews: {
|
reviews: {
|
||||||
Row: {
|
Row: {
|
||||||
content: string | null
|
content: string | null
|
||||||
@@ -367,6 +409,7 @@ export type Database = {
|
|||||||
park_id: string | null
|
park_id: string | null
|
||||||
photos: Json | null
|
photos: Json | null
|
||||||
rating: number
|
rating: number
|
||||||
|
report_count: number
|
||||||
ride_id: string | null
|
ride_id: string | null
|
||||||
title: string | null
|
title: string | null
|
||||||
total_votes: number | null
|
total_votes: number | null
|
||||||
@@ -386,6 +429,7 @@ export type Database = {
|
|||||||
park_id?: string | null
|
park_id?: string | null
|
||||||
photos?: Json | null
|
photos?: Json | null
|
||||||
rating: number
|
rating: number
|
||||||
|
report_count?: number
|
||||||
ride_id?: string | null
|
ride_id?: string | null
|
||||||
title?: string | null
|
title?: string | null
|
||||||
total_votes?: number | null
|
total_votes?: number | null
|
||||||
@@ -405,6 +449,7 @@ export type Database = {
|
|||||||
park_id?: string | null
|
park_id?: string | null
|
||||||
photos?: Json | null
|
photos?: Json | null
|
||||||
rating?: number
|
rating?: number
|
||||||
|
report_count?: number
|
||||||
ride_id?: string | null
|
ride_id?: string | null
|
||||||
title?: string | null
|
title?: string | null
|
||||||
total_votes?: number | null
|
total_votes?: number | null
|
||||||
@@ -637,6 +682,33 @@ export type Database = {
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
user_roles: {
|
||||||
|
Row: {
|
||||||
|
created_at: string
|
||||||
|
granted_at: string
|
||||||
|
granted_by: string | null
|
||||||
|
id: string
|
||||||
|
role: Database["public"]["Enums"]["app_role"]
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Insert: {
|
||||||
|
created_at?: string
|
||||||
|
granted_at?: string
|
||||||
|
granted_by?: string | null
|
||||||
|
id?: string
|
||||||
|
role: Database["public"]["Enums"]["app_role"]
|
||||||
|
user_id: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
created_at?: string
|
||||||
|
granted_at?: string
|
||||||
|
granted_by?: string | null
|
||||||
|
id?: string
|
||||||
|
role?: Database["public"]["Enums"]["app_role"]
|
||||||
|
user_id?: string
|
||||||
|
}
|
||||||
|
Relationships: []
|
||||||
|
}
|
||||||
user_top_lists: {
|
user_top_lists: {
|
||||||
Row: {
|
Row: {
|
||||||
created_at: string
|
created_at: string
|
||||||
@@ -678,6 +750,17 @@ export type Database = {
|
|||||||
[_ in never]: never
|
[_ in never]: never
|
||||||
}
|
}
|
||||||
Functions: {
|
Functions: {
|
||||||
|
has_role: {
|
||||||
|
Args: {
|
||||||
|
_role: Database["public"]["Enums"]["app_role"]
|
||||||
|
_user_id: string
|
||||||
|
}
|
||||||
|
Returns: boolean
|
||||||
|
}
|
||||||
|
is_moderator: {
|
||||||
|
Args: { _user_id: string }
|
||||||
|
Returns: boolean
|
||||||
|
}
|
||||||
update_company_ratings: {
|
update_company_ratings: {
|
||||||
Args: { target_company_id: string }
|
Args: { target_company_id: string }
|
||||||
Returns: undefined
|
Returns: undefined
|
||||||
@@ -692,7 +775,7 @@ export type Database = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Enums: {
|
Enums: {
|
||||||
[_ in never]: never
|
app_role: "admin" | "moderator" | "user"
|
||||||
}
|
}
|
||||||
CompositeTypes: {
|
CompositeTypes: {
|
||||||
[_ in never]: never
|
[_ in never]: never
|
||||||
@@ -819,6 +902,8 @@ export type CompositeTypes<
|
|||||||
|
|
||||||
export const Constants = {
|
export const Constants = {
|
||||||
public: {
|
public: {
|
||||||
Enums: {},
|
Enums: {
|
||||||
|
app_role: ["admin", "moderator", "user"],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
} as const
|
} as const
|
||||||
|
|||||||
162
src/pages/Admin.tsx
Normal file
162
src/pages/Admin.tsx
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { Shield, Users, FileText, Flag, AlertCircle } from 'lucide-react';
|
||||||
|
import { useUserRole } from '@/hooks/useUserRole';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||||
|
import { ModerationQueue } from '@/components/moderation/ModerationQueue';
|
||||||
|
import { ReportsQueue } from '@/components/moderation/ReportsQueue';
|
||||||
|
import { UserRoleManager } from '@/components/moderation/UserRoleManager';
|
||||||
|
|
||||||
|
export default function Admin() {
|
||||||
|
const { user, loading: authLoading } = useAuth();
|
||||||
|
const { isModerator, loading: roleLoading } = useUserRole();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!authLoading && !roleLoading) {
|
||||||
|
if (!user) {
|
||||||
|
navigate('/auth');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isModerator()) {
|
||||||
|
navigate('/');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [user, authLoading, roleLoading, isModerator, navigate]);
|
||||||
|
|
||||||
|
if (authLoading || roleLoading) {
|
||||||
|
return (
|
||||||
|
<div className="container mx-auto px-4 py-8">
|
||||||
|
<div className="flex items-center justify-center min-h-[400px]">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
|
||||||
|
<p className="text-muted-foreground">Loading admin panel...</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user || !isModerator()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container mx-auto px-4 py-8">
|
||||||
|
<div className="mb-8">
|
||||||
|
<div className="flex items-center gap-3 mb-2">
|
||||||
|
<Shield className="w-8 h-8 text-primary" />
|
||||||
|
<h1 className="text-3xl font-bold">Admin Dashboard</h1>
|
||||||
|
</div>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Manage content moderation and user roles
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium">Pending Reviews</CardTitle>
|
||||||
|
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="text-2xl font-bold">--</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Reviews awaiting moderation
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium">Open Reports</CardTitle>
|
||||||
|
<Flag className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="text-2xl font-bold">--</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
User reports to review
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||||
|
<CardTitle className="text-sm font-medium">Flagged Content</CardTitle>
|
||||||
|
<AlertCircle className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="text-2xl font-bold">--</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Auto-flagged items
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Tabs defaultValue="queue" className="space-y-6">
|
||||||
|
<TabsList className="grid w-full grid-cols-3">
|
||||||
|
<TabsTrigger value="queue" className="flex items-center gap-2">
|
||||||
|
<FileText className="w-4 h-4" />
|
||||||
|
Moderation Queue
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="reports" className="flex items-center gap-2">
|
||||||
|
<Flag className="w-4 h-4" />
|
||||||
|
Reports
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="users" className="flex items-center gap-2">
|
||||||
|
<Users className="w-4 h-4" />
|
||||||
|
User Roles
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
|
||||||
|
<TabsContent value="queue">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Content Moderation Queue</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Review and moderate pending content submissions and flagged reviews
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ModerationQueue />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="reports">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>User Reports</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Review reports submitted by users about inappropriate content
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<ReportsQueue />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="users">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>User Role Management</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Manage moderator and admin privileges for users
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<UserRoleManager />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
-- Create user roles enum
|
||||||
|
CREATE TYPE public.app_role AS ENUM ('admin', 'moderator', 'user');
|
||||||
|
|
||||||
|
-- Create user_roles table
|
||||||
|
CREATE TABLE public.user_roles (
|
||||||
|
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||||
|
role public.app_role NOT NULL,
|
||||||
|
granted_by UUID REFERENCES auth.users(id),
|
||||||
|
granted_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE(user_id, role)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Enable RLS on user_roles
|
||||||
|
ALTER TABLE public.user_roles ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
-- Create reports table
|
||||||
|
CREATE TABLE public.reports (
|
||||||
|
id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||||
|
reporter_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||||
|
reported_entity_type TEXT NOT NULL CHECK (reported_entity_type IN ('review', 'profile', 'content_submission')),
|
||||||
|
reported_entity_id UUID NOT NULL,
|
||||||
|
report_type TEXT NOT NULL CHECK (report_type IN ('spam', 'inappropriate', 'harassment', 'fake_info', 'offensive')),
|
||||||
|
reason TEXT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'reviewed', 'dismissed')),
|
||||||
|
reviewed_by UUID REFERENCES auth.users(id),
|
||||||
|
reviewed_at TIMESTAMP WITH TIME ZONE,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Enable RLS on reports
|
||||||
|
ALTER TABLE public.reports ENABLE ROW LEVEL SECURITY;
|
||||||
|
|
||||||
|
-- Add report_count to reviews table for auto-flagging
|
||||||
|
ALTER TABLE public.reviews ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- Create security definer function to check user roles
|
||||||
|
CREATE OR REPLACE FUNCTION public.has_role(_user_id UUID, _role public.app_role)
|
||||||
|
RETURNS BOOLEAN
|
||||||
|
LANGUAGE SQL
|
||||||
|
STABLE
|
||||||
|
SECURITY DEFINER
|
||||||
|
SET search_path = public
|
||||||
|
AS $$
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM public.user_roles
|
||||||
|
WHERE user_id = _user_id
|
||||||
|
AND role = _role
|
||||||
|
)
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- Create function to check if user is moderator or admin
|
||||||
|
CREATE OR REPLACE FUNCTION public.is_moderator(_user_id UUID)
|
||||||
|
RETURNS BOOLEAN
|
||||||
|
LANGUAGE SQL
|
||||||
|
STABLE
|
||||||
|
SECURITY DEFINER
|
||||||
|
SET search_path = public
|
||||||
|
AS $$
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM public.user_roles
|
||||||
|
WHERE user_id = _user_id
|
||||||
|
AND role IN ('moderator', 'admin')
|
||||||
|
)
|
||||||
|
$$;
|
||||||
|
|
||||||
|
-- RLS Policies for user_roles
|
||||||
|
CREATE POLICY "Admins can manage all user roles"
|
||||||
|
ON public.user_roles
|
||||||
|
FOR ALL
|
||||||
|
USING (public.has_role(auth.uid(), 'admin'));
|
||||||
|
|
||||||
|
CREATE POLICY "Users can view their own roles"
|
||||||
|
ON public.user_roles
|
||||||
|
FOR SELECT
|
||||||
|
USING (auth.uid() = user_id);
|
||||||
|
|
||||||
|
-- RLS Policies for reports
|
||||||
|
CREATE POLICY "Users can create reports"
|
||||||
|
ON public.reports
|
||||||
|
FOR INSERT
|
||||||
|
WITH CHECK (auth.uid() = reporter_id);
|
||||||
|
|
||||||
|
CREATE POLICY "Users can view their own reports"
|
||||||
|
ON public.reports
|
||||||
|
FOR SELECT
|
||||||
|
USING (auth.uid() = reporter_id);
|
||||||
|
|
||||||
|
CREATE POLICY "Moderators can view all reports"
|
||||||
|
ON public.reports
|
||||||
|
FOR SELECT
|
||||||
|
USING (public.is_moderator(auth.uid()));
|
||||||
|
|
||||||
|
CREATE POLICY "Moderators can update reports"
|
||||||
|
ON public.reports
|
||||||
|
FOR UPDATE
|
||||||
|
USING (public.is_moderator(auth.uid()));
|
||||||
|
|
||||||
|
-- Update RLS policies for reviews to allow moderator access
|
||||||
|
CREATE POLICY "Moderators can view all reviews"
|
||||||
|
ON public.reviews
|
||||||
|
FOR SELECT
|
||||||
|
USING (public.is_moderator(auth.uid()));
|
||||||
|
|
||||||
|
CREATE POLICY "Moderators can update review status"
|
||||||
|
ON public.reviews
|
||||||
|
FOR UPDATE
|
||||||
|
USING (public.is_moderator(auth.uid()));
|
||||||
|
|
||||||
|
-- Update RLS policies for content_submissions to allow moderator access
|
||||||
|
CREATE POLICY "Moderators can view all content submissions"
|
||||||
|
ON public.content_submissions
|
||||||
|
FOR SELECT
|
||||||
|
USING (public.is_moderator(auth.uid()));
|
||||||
|
|
||||||
|
CREATE POLICY "Moderators can update content submissions"
|
||||||
|
ON public.content_submissions
|
||||||
|
FOR UPDATE
|
||||||
|
USING (public.is_moderator(auth.uid()));
|
||||||
|
|
||||||
|
-- Create trigger to update report_count on reviews when reports are created
|
||||||
|
CREATE OR REPLACE FUNCTION public.update_report_count()
|
||||||
|
RETURNS TRIGGER
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
SECURITY DEFINER
|
||||||
|
SET search_path = public
|
||||||
|
AS $$
|
||||||
|
BEGIN
|
||||||
|
IF NEW.reported_entity_type = 'review' THEN
|
||||||
|
UPDATE public.reviews
|
||||||
|
SET report_count = report_count + 1,
|
||||||
|
moderation_status = CASE
|
||||||
|
WHEN report_count + 1 >= 3 THEN 'flagged'
|
||||||
|
ELSE moderation_status
|
||||||
|
END
|
||||||
|
WHERE id = NEW.reported_entity_id;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
|
|
||||||
|
CREATE TRIGGER increment_report_count
|
||||||
|
AFTER INSERT ON public.reports
|
||||||
|
FOR EACH ROW
|
||||||
|
WHEN (NEW.reported_entity_type = 'review')
|
||||||
|
EXECUTE FUNCTION public.update_report_count();
|
||||||
|
|
||||||
|
-- Create trigger for updating updated_at on reports
|
||||||
|
CREATE TRIGGER update_reports_updated_at
|
||||||
|
BEFORE UPDATE ON public.reports
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION public.update_updated_at_column();
|
||||||
Reference in New Issue
Block a user