Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(rbac/ui): hide write controls on Manage Prompts & Manage Topics for non-admin/manager roles (#141)

Gökhan Geyik589accdf20ea
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
index 76888b270..82511ccc8 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/prompts/page.tsx
@@ -26,9 +26,10 @@ import {
} from '@/components/ui/select';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
-import { Loader2, Plus, Sparkles, Save, X, Play, Search } from 'lucide-react';
+import { Loader2, Plus, Sparkles, Save, X, Play, Search, Lock } from 'lucide-react';
import { MODEL_GROUPS, ALL_MODELS, SCRAPER_GROUPS, ALL_SCRAPERS } from '@/config/prompt-options';
import { usePlanContext } from '@/components/providers/plan-provider';
+import { useUserRole } from '@/hooks/use-user-role';
import { PLANS } from '@/config/plans';
import { saveTrackingJob } from '@/lib/tracking-job-store';
import { useRouter } from '@/i18n/navigation';
@@ -73,6 +74,7 @@ export default function PromptsPage() {
const [manualCategory, setManualCategory] = useState('');
const [generateTopics, setGenerateTopics] = useState<string[] | null>(null);
const { planId } = usePlanContext();
+ const { canManage } = useUserRole();
const allowedScraperIds = useMemo(() => {
const allowed = PLANS[planId].limits.allowedScrapers;
return allowed ? [...allowed] : ALL_SCRAPERS.map((s) => s.id);
@@ -479,266 +481,288 @@ export default function PromptsPage() {
return (
<div className="space-y-6">
- {/* Add Prompt + AI Generate */}
- <div className="grid gap-4 md:grid-cols-2">
- {/* Manual Add */}
- <Card>
- <CardHeader className="pb-3">
- <CardTitle className="flex items-center gap-2 text-base">
- <Plus className="h-4 w-4" />
- Add Prompt
- </CardTitle>
- </CardHeader>
- <CardContent>
- <div className="space-y-3">
- <Input
- placeholder="e.g. Best project management tools for startups"
- value={manualText}
- onChange={(e) => setManualText(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === 'Enter' && manualText.trim()) handleAddManualPrompt();
- }}
- />
+ {/* Read-only banner — non-admin / non-manager roles can't INSERT into
+ prompts / prompt_sets at the DB layer (RLS). We hide the write
+ controls below so they don't hit a generic "Failed to save"
+ toast after the request gets rejected. */}
+ {!canManage && (
+ <div className="flex items-start gap-3 rounded-lg border bg-muted/40 p-4 text-sm">
+ <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div>
+ <p className="font-medium">Read-only access</p>
+ <p className="mt-1 text-muted-foreground">
+ Your role can view tracked prompts but not add, edit, or delete them. Ask an admin or
+ manager to make changes.
+ </p>
+ </div>
+ </div>
+ )}
+ {/* Add Prompt + AI Generate */}
+ {canManage && (
+ <div className="grid gap-4 md:grid-cols-2">
+ {/* Manual Add */}
+ <Card>
+ <CardHeader className="pb-3">
+ <CardTitle className="flex items-center gap-2 text-base">
+ <Plus className="h-4 w-4" />
+ Add Prompt
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
<div className="space-y-3">
- {/* Topic */}
- <div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Topic
- </label>
- {topics.length > 0 ? (
- <Select value={manualCategory} onValueChange={(v) => v && setManualCategory(v)}>
+ <Input
+ placeholder="e.g. Best project management tools for startups"
+ value={manualText}
+ onChange={(e) => setManualText(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && manualText.trim()) handleAddManualPrompt();
+ }}
+ />
+
+ <div className="space-y-3">
+ {/* Topic */}
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ Topic
+ </label>
+ {topics.length > 0 ? (
+ <Select
+ value={manualCategory}
+ onValueChange={(v) => v && setManualCategory(v)}
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue placeholder="Select a topic" />
+ </SelectTrigger>
+ <SelectContent>
+ {topics.map((topic) => (
+ <SelectItem key={topic.id} value={topic.name}>
+ {topic.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <p className="text-xs text-muted-foreground py-2">
+ No topics defined yet. Add topics in brand settings.
+ </p>
+ )}
+ </div>
+
+ {/* Platform & Models — combined select */}
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ Platform & Models
+ </label>
+ <Select
+ value="__placeholder__"
+ onValueChange={(v) => {
+ if (!v || v === '__placeholder__') return;
+ if (visibleModels.some((m) => m.id === v) && !manualModels.includes(v)) {
+ setManualModels((prev) => [...prev, v]);
+ } else if (
+ visibleScrapers.some((s) => s.id === v) &&
+ !manualScrapers.includes(v)
+ ) {
+ setManualScrapers((prev) => [...prev, v]);
+ }
+ }}
+ >
<SelectTrigger className="w-full">
- <SelectValue placeholder="Select a topic" />
+ <span className="truncate text-muted-foreground">
+ {manualModels.length + manualScrapers.length > 0
+ ? `${manualModels.length + manualScrapers.length} selected`
+ : 'Select platform & models'}
+ </span>
</SelectTrigger>
<SelectContent>
- {topics.map((topic) => (
- <SelectItem key={topic.id} value={topic.name}>
- {topic.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- ) : (
- <p className="text-xs text-muted-foreground py-2">
- No topics defined yet. Add topics in brand settings.
- </p>
- )}
- </div>
-
- {/* Platform & Models — combined select */}
- <div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Platform & Models
- </label>
- <Select
- value="__placeholder__"
- onValueChange={(v) => {
- if (!v || v === '__placeholder__') return;
- if (visibleModels.some((m) => m.id === v) && !manualModels.includes(v)) {
- setManualModels((prev) => [...prev, v]);
- } else if (
- visibleScrapers.some((s) => s.id === v) &&
- !manualScrapers.includes(v)
- ) {
- setManualScrapers((prev) => [...prev, v]);
- }
- }}
- >
- <SelectTrigger className="w-full">
- <span className="truncate text-muted-foreground">
- {manualModels.length + manualScrapers.length > 0
- ? `${manualModels.length + manualScrapers.length} selected`
- : 'Select platform & models'}
- </span>
- </SelectTrigger>
- <SelectContent>
- {SCRAPER_GROUPS.map((group) => {
- const scrapers = group.scrapers.filter((s) =>
- visibleScrapers.some((vs) => vs.id === s.id),
- );
- if (scrapers.length === 0) return null;
- return (
- <div key={group.provider}>
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
- {group.provider} (Scraper)
+ {SCRAPER_GROUPS.map((group) => {
+ const scrapers = group.scrapers.filter((s) =>
+ visibleScrapers.some((vs) => vs.id === s.id),
+ );
+ if (scrapers.length === 0) return null;
+ return (
+ <div key={group.provider}>
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
+ {group.provider} (Scraper)
+ </div>
+ {scrapers.map((s) => (
+ <SelectItem
+ key={s.id}
+ value={s.id}
+ disabled={manualScrapers.includes(s.id)}
+ >
+ <div>
+ <div>{s.label}</div>
+ <div className="text-[10px] text-muted-foreground font-mono">
+ {s.id}
+ </div>
+ </div>
+ </SelectItem>
+ ))}
</div>
- {scrapers.map((s) => (
- <SelectItem
- key={s.id}
- value={s.id}
- disabled={manualScrapers.includes(s.id)}
- >
- <div>
- <div>{s.label}</div>
- <div className="text-[10px] text-muted-foreground font-mono">
- {s.id}
+ );
+ })}
+ {MODEL_GROUPS.map((group) => {
+ const groupModels = group.models.filter((m) =>
+ visibleModels.some((vm) => vm.id === m.id),
+ );
+ if (groupModels.length === 0) return null;
+ return (
+ <div key={group.provider}>
+ <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
+ {group.provider} (API)
+ </div>
+ {groupModels.map((m) => (
+ <SelectItem
+ key={m.id}
+ value={m.id}
+ disabled={manualModels.includes(m.id)}
+ >
+ <div>
+ <div>{m.label}</div>
+ <div className="text-[10px] text-muted-foreground font-mono">
+ {m.id}
+ </div>
</div>
- </div>
- </SelectItem>
- ))}
- </div>
- );
- })}
- {MODEL_GROUPS.map((group) => {
- const groupModels = group.models.filter((m) =>
- visibleModels.some((vm) => vm.id === m.id),
- );
- if (groupModels.length === 0) return null;
- return (
- <div key={group.provider}>
- <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
- {group.provider} (API)
+ </SelectItem>
+ ))}
</div>
- {groupModels.map((m) => (
- <SelectItem
- key={m.id}
- value={m.id}
- disabled={manualModels.includes(m.id)}
+ );
+ })}
+ </SelectContent>
+ </Select>
+ {(manualModels.length > 0 || manualScrapers.length > 0) && (
+ <div className="mt-1.5 flex flex-wrap gap-1">
+ {manualScrapers.map((id) => {
+ const s = ALL_SCRAPERS.find((as_) => as_.id === id);
+ return (
+ <Badge key={id} variant="outline" className="gap-1 text-xs">
+ {s?.label ?? id}
+ <button
+ type="button"
+ onClick={() => setManualScrapers((p) => p.filter((i) => i !== id))}
>
- <div>
- <div>{m.label}</div>
- <div className="text-[10px] text-muted-foreground font-mono">
- {m.id}
- </div>
- </div>
- </SelectItem>
- ))}
- </div>
- );
- })}
- </SelectContent>
- </Select>
- {(manualModels.length > 0 || manualScrapers.length > 0) && (
- <div className="mt-1.5 flex flex-wrap gap-1">
- {manualScrapers.map((id) => {
- const s = ALL_SCRAPERS.find((as_) => as_.id === id);
- return (
- <Badge key={id} variant="outline" className="gap-1 text-xs">
- {s?.label ?? id}
- <button
- type="button"
- onClick={() => setManualScrapers((p) => p.filter((i) => i !== id))}
- >
- <X className="h-3 w-3" />
- </button>
- </Badge>
- );
- })}
- {manualModels.map((id) => {
- const m = ALL_MODELS.find((am) => am.id === id);
+ <X className="h-3 w-3" />
+ </button>
+ </Badge>
+ );
+ })}
+ {manualModels.map((id) => {
+ const m = ALL_MODELS.find((am) => am.id === id);
+ return (
+ <Badge key={id} variant="secondary" className="gap-1 text-xs">
+ {m?.label ?? id}
+ <button
+ type="button"
+ onClick={() => setManualModels((p) => p.filter((i) => i !== id))}
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </Badge>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <Button
+ onClick={handleAddManualPrompt}
+ disabled={
+ isAddingManual ||
+ !manualText.trim() ||
+ (manualScrapers.length === 0 && manualModels.length === 0)
+ }
+ className="w-full"
+ >
+ {isAddingManual ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <Plus className="mr-2 h-4 w-4" />
+ )}
+ Add Prompt
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+
+ {/* AI Generate */}
+ <Card>
+ <CardHeader className="pb-3">
+ <CardTitle className="flex items-center gap-2 text-base">
+ <Sparkles className="h-4 w-4" />
+ AI Generate
+ </CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-3">
+ <p className="text-sm text-muted-foreground">
+ Select topics and generate 5 optimized search prompts per topic using AI.
+ </p>
+ {topics.length > 0 ? (
+ <div>
+ <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
+ Topics
+ </label>
+ <div className="flex flex-wrap gap-1.5">
+ {topics.map((topic) => {
+ const selected = generateTopics?.includes(topic.name) ?? false;
return (
- <Badge key={id} variant="secondary" className="gap-1 text-xs">
- {m?.label ?? id}
- <button
- type="button"
- onClick={() => setManualModels((p) => p.filter((i) => i !== id))}
- >
- <X className="h-3 w-3" />
- </button>
+ <Badge
+ key={topic.id}
+ variant={selected ? 'default' : 'outline'}
+ className="cursor-pointer select-none"
+ onClick={() =>
+ setGenerateTopics((prev) =>
+ selected
+ ? (prev ?? []).filter((t) => t !== topic.name)
+ : [...(prev ?? []), topic.name],
+ )
+ }
+ >
+ {topic.name}
</Badge>
);
})}
</div>
- )}
- </div>
- </div>
-
- <Button
- onClick={handleAddManualPrompt}
- disabled={
- isAddingManual ||
- !manualText.trim() ||
- (manualScrapers.length === 0 && manualModels.length === 0)
- }
- className="w-full"
- >
- {isAddingManual ? (
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- ) : (
- <Plus className="mr-2 h-4 w-4" />
- )}
- Add Prompt
- </Button>
- </div>
- </CardContent>
- </Card>
-
- {/* AI Generate */}
- <Card>
- <CardHeader className="pb-3">
- <CardTitle className="flex items-center gap-2 text-base">
- <Sparkles className="h-4 w-4" />
- AI Generate
- </CardTitle>
- </CardHeader>
- <CardContent>
- <div className="space-y-3">
- <p className="text-sm text-muted-foreground">
- Select topics and generate 5 optimized search prompts per topic using AI.
- </p>
- {topics.length > 0 ? (
- <div>
- <label className="mb-1.5 block text-xs font-medium text-muted-foreground">
- Topics
- </label>
- <div className="flex flex-wrap gap-1.5">
- {topics.map((topic) => {
- const selected = generateTopics?.includes(topic.name) ?? false;
- return (
- <Badge
- key={topic.id}
- variant={selected ? 'default' : 'outline'}
- className="cursor-pointer select-none"
- onClick={() =>
- setGenerateTopics((prev) =>
- selected
- ? (prev ?? []).filter((t) => t !== topic.name)
- : [...(prev ?? []), topic.name],
- )
- }
- >
- {topic.name}
- </Badge>
- );
- })}
+ {generateTopics && generateTopics.length > 0 && (
+ <p className="mt-1.5 text-xs text-muted-foreground">
+ {generateTopics.length} topic{generateTopics.length !== 1 ? 's' : ''}{' '}
+ selected — {generateTopics.length * 5} prompts will be generated
+ </p>
+ )}
</div>
- {generateTopics && generateTopics.length > 0 && (
- <p className="mt-1.5 text-xs text-muted-foreground">
- {generateTopics.length} topic{generateTopics.length !== 1 ? 's' : ''} selected
- — {generateTopics.length * 5} prompts will be generated
- </p>
- )}
- </div>
- ) : (
- <p className="text-xs text-muted-foreground py-2">
- No topics defined yet. Add topics in brand settings first.
- </p>
- )}
- <Button
- onClick={handleGenerate}
- disabled={isGenerating || !generateTopics || generateTopics.length === 0}
- className="w-full"
- >
- {isGenerating ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Generating...
- </>
) : (
- <>
- <Sparkles className="mr-2 h-4 w-4" />
- Generate Prompts
- </>
+ <p className="text-xs text-muted-foreground py-2">
+ No topics defined yet. Add topics in brand settings first.
+ </p>
)}
- </Button>
- </div>
- </CardContent>
- </Card>
- </div>
+ <Button
+ onClick={handleGenerate}
+ disabled={isGenerating || !generateTopics || generateTopics.length === 0}
+ className="w-full"
+ >
+ {isGenerating ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Generating...
+ </>
+ ) : (
+ <>
+ <Sparkles className="mr-2 h-4 w-4" />
+ Generate Prompts
+ </>
+ )}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ )}
{/* AI Suggestions Review (shown only when generated) */}
- {suggestions.length > 0 && (
+ {canManage && suggestions.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Review AI Suggestions</CardTitle>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
index c300197eb..79889edf5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/topics/page.tsx
@@ -15,7 +15,8 @@ import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
-import { Check, Loader2, Pencil, Plus, Tag, Trash2, X } from 'lucide-react';
+import { Check, Loader2, Lock, Pencil, Plus, Tag, Trash2, X } from 'lucide-react';
+import { useUserRole } from '@/hooks/use-user-role';
import {
Dialog,
DialogClose,
@@ -41,6 +42,7 @@ export default function BrandTopicsPage({ params }: PageProps) {
const [newName, setNewName] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState('');
+ const { canManage } = useUserRole();
const load = useCallback(async () => {
setIsLoading(true);
@@ -172,56 +174,60 @@ export default function BrandTopicsPage({ params }: PageProps) {
) : (
<>
<p className="flex-1 truncate text-sm font-medium">{topic.name}</p>
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7 shrink-0"
- onClick={() => {
- setEditingId(topic.id);
- setEditName(topic.name);
- }}
- >
- <Pencil className="h-3.5 w-3.5" />
- </Button>
- <Dialog>
- <DialogTrigger
- render={
- <Button
- variant="ghost"
- size="icon"
- className="h-7 w-7 shrink-0 text-destructive hover:text-destructive"
- />
- }
- >
- <Trash2 className="h-3.5 w-3.5" />
- </DialogTrigger>
- <DialogContent className="sm:max-w-sm">
- <DialogHeader>
- <DialogTitle>Delete Topic</DialogTitle>
- <DialogDescription>
- Are you sure you want to delete &quot;{topic.name}&quot;?
- {(promptCounts[topic.id] ?? 0) > 0
- ? ` ${promptCounts[topic.id]} prompt${promptCounts[topic.id] === 1 ? '' : 's'} using this topic will become uncategorized.`
- : ' No prompts are using this topic.'}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" />}>
- Cancel
- </DialogClose>
- <DialogClose
+ {canManage && (
+ <>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 shrink-0"
+ onClick={() => {
+ setEditingId(topic.id);
+ setEditName(topic.name);
+ }}
+ >
+ <Pencil className="h-3.5 w-3.5" />
+ </Button>
+ <Dialog>
+ <DialogTrigger
render={
<Button
- variant="destructive"
- onClick={() => handleDelete(topic.id)}
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7 shrink-0 text-destructive hover:text-destructive"
/>
}
>
- Delete
- </DialogClose>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <Trash2 className="h-3.5 w-3.5" />
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Delete Topic</DialogTitle>
+ <DialogDescription>
+ Are you sure you want to delete &quot;{topic.name}&quot;?
+ {(promptCounts[topic.id] ?? 0) > 0
+ ? ` ${promptCounts[topic.id]} prompt${promptCounts[topic.id] === 1 ? '' : 's'} using this topic will become uncategorized.`
+ : ' No prompts are using this topic.'}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>
+ Cancel
+ </DialogClose>
+ <DialogClose
+ render={
+ <Button
+ variant="destructive"
+ onClick={() => handleDelete(topic.id)}
+ />
+ }
+ >
+ Delete
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ )}
</>
)}
</div>
@@ -237,33 +243,52 @@ export default function BrandTopicsPage({ params }: PageProps) {
</div>
)}
- <Separator />
+ {canManage ? (
+ <>
+ <Separator />
- <div className="space-y-2">
- <Label className="text-sm font-medium">Add Topic</Label>
- <div className="flex gap-2">
- <Input
- placeholder="e.g. Industry, Comparison, How-to..."
- value={newName}
- onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAdd()}
- className="flex-1"
- />
- <Button
- variant="outline"
- onClick={handleAdd}
- disabled={isAdding || !newName.trim()}
- className="gap-1.5 shrink-0"
- >
- {isAdding ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Plus className="h-4 w-4" />
- )}
- Add
- </Button>
+ <div className="space-y-2">
+ <Label className="text-sm font-medium">Add Topic</Label>
+ <div className="flex gap-2">
+ <Input
+ placeholder="e.g. Industry, Comparison, How-to..."
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && newName.trim() && handleAdd()}
+ className="flex-1"
+ />
+ <Button
+ variant="outline"
+ onClick={handleAdd}
+ disabled={isAdding || !newName.trim()}
+ className="gap-1.5 shrink-0"
+ >
+ {isAdding ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Plus className="h-4 w-4" />
+ )}
+ Add
+ </Button>
+ </div>
+ </div>
+ </>
+ ) : (
+ // Read-only banner — non-admin / non-manager roles can't INSERT
+ // into topics at the DB layer (RLS). Hide the Add form and
+ // surface the reason instead of letting them hit a generic
+ // "Failed to add topic" toast.
+ <div className="flex items-start gap-3 rounded-lg border bg-muted/40 p-3 text-sm">
+ <Lock className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div>
+ <p className="font-medium">Read-only access</p>
+ <p className="mt-1 text-muted-foreground">
+ Your role can view topics but not add, rename, or delete them. Ask an admin or
+ manager to make changes.
+ </p>
+ </div>
</div>
- </div>
+ )}
</>
)}
</CardContent>
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index cda0dbcf9..f786dca98 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -5,6 +5,7 @@ import { SidebarErrorBoundary } from '@/components/layout/sidebar-error-boundary
import { MobileNav } from '@/components/layout/mobile-nav';
import { AuthProvider } from '@/components/providers/auth-provider';
import { PlanProvider } from '@/components/providers/plan-provider';
+import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';
import { BrandLoader } from '@/components/providers/brand-loader';
import { BrandGuard } from '@/components/providers/brand-guard';
import { getBrands } from '@/lib/actions/brand';
@@ -22,7 +23,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
const { data: profile } = await supabase
.from('profiles')
- .select('organization_id, onboarding_completed')
+ .select('organization_id, onboarding_completed, role')
.eq('id', user.id)
.single();
@@ -30,6 +31,8 @@ export default async function DashboardLayout({ children }: { children: React.Re
redirect('/dashboard/onboarding');
}
+ const role = (profile.role ?? 'analyst') as TeamRole;
+
const [{ data: org }, brands] = await Promise.all([
supabase
.from('organizations')
@@ -54,24 +57,26 @@ export default async function DashboardLayout({ children }: { children: React.Re
<AuthProvider user={user} />
<BrandLoader brands={brands} />
<PlanProvider planId={planId}>
- <div className="flex h-screen overflow-hidden">
- {/* Desktop sidebar */}
- <div className="hidden md:flex md:flex-shrink-0">
- <SidebarErrorBoundary>
- <Sidebar />
- </SidebarErrorBoundary>
- </div>
+ <RoleProvider role={role}>
+ <div className="flex h-screen overflow-hidden">
+ {/* Desktop sidebar */}
+ <div className="hidden md:flex md:flex-shrink-0">
+ <SidebarErrorBoundary>
+ <Sidebar />
+ </SidebarErrorBoundary>
+ </div>
- {/* Main area */}
- <div className="flex flex-1 flex-col overflow-hidden">
- <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">
- <MobileNav />
+ {/* Main area */}
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex h-16 items-center border-b bg-card px-4 gap-3 md:hidden">
+ <MobileNav />
+ </div>
+ <main className="flex-1 overflow-y-auto bg-background p-6">
+ <BrandGuard>{children}</BrandGuard>
+ </main>
</div>
- <main className="flex-1 overflow-y-auto bg-background p-6">
- <BrandGuard>{children}</BrandGuard>
- </main>
</div>
- </div>
+ </RoleProvider>
</PlanProvider>
</>
);
diff --git a/web/src/components/auth/role-gate.tsx b/web/src/components/auth/role-gate.tsx
new file mode 100644
index 000000000..c0d99a488
--- /dev/null
+++ b/web/src/components/auth/role-gate.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { useUserRole } from '@/hooks/use-user-role';
+import type { TeamRole } from '@/components/providers/role-provider';
+
+/**
+ * Conditionally render children based on the current user's role.
+ *
+ * Tiny wrapper on top of {@link useUserRole}; sugar for cases where you'd
+ * otherwise sprinkle `if (!canManage) return null` around several pieces
+ * of JSX in the same component.
+ *
+ * ```tsx
+ * <RoleGate roles={['admin', 'manager']}>
+ * <Button onClick={handleSave}>Save</Button>
+ * </RoleGate>
+ *
+ * <RoleGate
+ * roles={['admin', 'manager']}
+ * fallback={<p className="text-sm">Ask an admin to edit this.</p>}
+ * >
+ * <EditForm />
+ * </RoleGate>
+ * ```
+ */
+export function RoleGate({
+ roles,
+ fallback = null,
+ children,
+}: {
+ roles: TeamRole[];
+ fallback?: React.ReactNode;
+ children: React.ReactNode;
+}) {
+ const { role } = useUserRole();
+ return roles.includes(role) ? <>{children}</> : <>{fallback}</>;
+}
diff --git a/web/src/components/providers/role-provider.tsx b/web/src/components/providers/role-provider.tsx
new file mode 100644
index 000000000..d834bd93d
--- /dev/null
+++ b/web/src/components/providers/role-provider.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import { createContext, type ReactNode } from 'react';
+
+/**
+ * Source of truth for the four roles `profiles.role` can hold. Kept here
+ * (next to the provider) so client components can import the type without
+ * pulling the `'use server'` boundary in `lib/actions/team.ts`.
+ *
+ * The DB-side RLS policies grant **write** access to `admin | manager` on
+ * the major resource tables (`prompts`, `prompt_sets`, `brands`,
+ * `brand_domains`, `content_opportunities`). `analyst` and `agency_partner`
+ * are read-only at the database layer — the UI mirrors that posture via
+ * `useUserRole().canManage` + `<RoleGate>`.
+ */
+export type TeamRole = 'admin' | 'manager' | 'analyst' | 'agency_partner';
+
+export interface RoleContextValue {
+ role: TeamRole;
+}
+
+// Default to the lowest-privilege role so a misconfigured tree fails safe
+// — write controls stay hidden if the provider didn't mount.
+export const RoleContext = createContext<RoleContextValue>({ role: 'analyst' });
+
+export function RoleProvider({ role, children }: { role: TeamRole; children: ReactNode }) {
+ return <RoleContext.Provider value={{ role }}>{children}</RoleContext.Provider>;
+}
diff --git a/web/src/hooks/use-user-role.ts b/web/src/hooks/use-user-role.ts
new file mode 100644
index 000000000..c7a914b96
--- /dev/null
+++ b/web/src/hooks/use-user-role.ts
@@ -0,0 +1,33 @@
+'use client';
+
+import { useContext } from 'react';
+import { RoleContext, type TeamRole } from '@/components/providers/role-provider';
+
+export interface UserRoleInfo {
+ role: TeamRole;
+ /** admin or manager — can write to prompts, brands, topics, etc. */
+ canManage: boolean;
+ /** admin only — can manage team members, API keys, billing, the Anthropic key. */
+ canAdmin: boolean;
+}
+
+/**
+ * Read the current user's organizational role from `<RoleProvider>` and
+ * project it into two derived flags the UI cares about. `canManage`
+ * matches the admin-or-manager RLS gate used across `prompts`,
+ * `prompt_sets`, `brand_domains`, `content_opportunities`, etc.;
+ * `canAdmin` is the stricter admin-only gate used by team management
+ * and the Settings → Agent API key.
+ *
+ * The plan-gating equivalent is [`useFeatureGate`](./use-feature-gate.ts).
+ * They compose cleanly: feature gate decides "is this product surface
+ * available at all?", role gate decides "is this user allowed to write?"
+ */
+export function useUserRole(): UserRoleInfo {
+ const { role } = useContext(RoleContext);
+ return {
+ role,
+ canManage: role === 'admin' || role === 'manager',
+ canAdmin: role === 'admin',
+ };
+}