Merge pull request #108 from trypostit/fix/role-permissions-audit

fix(permissions): enforce workspace roles across backend and UI
This commit is contained in:
Paulo Castellano 2026-06-22 18:17:24 -03:00 committed by GitHub
commit d9e250dd82
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
36 changed files with 515 additions and 118 deletions

View file

@ -42,6 +42,8 @@ public function index(Request $request): Response
{
$workspace = $request->user()->currentWorkspace;
$this->authorize('view', $workspace);
$accounts = $workspace->socialAccounts()
->where('is_active', true)
->whereIn('platform', self::SUPPORTED_PLATFORMS)

View file

@ -48,6 +48,8 @@ class AutomationController extends Controller
{
public function index(ListAutomations $list): Response
{
$this->authorize('viewAny', Automation::class);
$workspace = request()->user()->currentWorkspace;
$automations = Inertia::scroll(fn () => AutomationResource::collection(
@ -61,6 +63,8 @@ public function index(ListAutomations $list): Response
public function store(StoreAutomationRequest $request, CreateAutomation $create): RedirectResponse
{
$this->authorize('create', Automation::class);
$automation = $create(
$request->user()->currentWorkspace,
$request->user(),
@ -71,6 +75,8 @@ public function store(StoreAutomationRequest $request, CreateAutomation $create)
public function show(Automation $automation): RedirectResponse
{
$this->authorize('view', $automation);
return redirect()->route('app.automations.workflow', $automation->id);
}

View file

@ -180,7 +180,9 @@ public function store(StorePostRequest $request): RedirectResponse|\Symfony\Comp
session()->flash('flash.banner', __('posts.flash.connect_first'));
session()->flash('flash.bannerStyle', 'danger');
return redirect()->route('app.accounts');
return $request->user()->can('manageAccounts', $workspace)
? redirect()->route('app.accounts')
: redirect()->route('app.calendar');
}
$post = CreatePost::execute($workspace, $request->user(), [
@ -232,13 +234,15 @@ public function edit(Request $request, Post $post): Response|RedirectResponse
return redirect()->route('app.workspaces.create');
}
$this->authorize('update', $post);
$this->authorize('view', $post);
if (PostStatusRules::blocksEditing($post)) {
return redirect()->route('app.posts.show', $post);
}
SyncPostPlatforms::execute($post);
if ($request->user()->can('update', $post)) {
SyncPostPlatforms::execute($post);
}
$post->load(['postPlatforms.socialAccount', 'labels']);
$socialAccounts = $workspace->socialAccounts()->active()->get();

View file

@ -41,7 +41,7 @@ public function index(Request $request): Response|RedirectResponse
return redirect()->route('app.workspaces.create');
}
$this->authorize('view', $workspace);
$this->authorize('manageAccounts', $workspace);
$platforms = collect(SocialPlatform::enabled())->map(fn ($platform) => [
'value' => $platform->value,

View file

@ -21,17 +21,20 @@ public function view(User $user, Automation $automation): bool
public function create(User $user): bool
{
return $user->currentWorkspace !== null;
return $user->currentWorkspace !== null
&& $user->can('createPost', $user->currentWorkspace);
}
public function update(User $user, Automation $automation): bool
{
return $automation->workspace_id === $user->current_workspace_id;
return $automation->workspace_id === $user->current_workspace_id
&& $user->can('createPost', $user->currentWorkspace);
}
public function delete(User $user, Automation $automation): bool
{
return $automation->workspace_id === $user->current_workspace_id;
return $automation->workspace_id === $user->current_workspace_id
&& $user->can('createPost', $user->currentWorkspace);
}
public function activate(User $user, Automation $automation): bool

View file

@ -25,7 +25,8 @@ public function view(User $user, Post $post): bool|Response
}
/**
* Authorize updating a post. Same workspace-tenancy guard as `view`.
* Authorize updating a post: tenancy guard (404 across tenants) then the
* role gate — viewers are read-only (403).
*/
public function update(User $user, Post $post): bool|Response
{
@ -33,11 +34,12 @@ public function update(User $user, Post $post): bool|Response
return Response::denyAsNotFound();
}
return true;
return $user->can('createPost', $user->currentWorkspace);
}
/**
* Authorize deleting a post. Same workspace-tenancy guard as `view`.
* Authorize deleting a post: tenancy guard (404 across tenants) then the
* same role gate as `update` — viewers are read-only (403).
*/
public function delete(User $user, Post $post): bool|Response
{
@ -45,7 +47,7 @@ public function delete(User $user, Post $post): bool|Response
return Response::denyAsNotFound();
}
return true;
return $user->can('createPost', $user->currentWorkspace);
}
/**

View file

@ -388,6 +388,7 @@
],
'status' => [
'pending' => 'Pending',
'scheduled' => 'Scheduled',
'published' => 'Published',
'publishing' => 'Publishing...',

View file

@ -24,7 +24,7 @@
'groups' => [
'posts' => 'Posts',
'workspace' => 'Workspace',
'support' => 'Support',
'others' => 'Others',
],
'analytics' => 'Analytics',
@ -54,9 +54,8 @@
'no_notifications' => 'No notifications',
'support' => [
'discord' => 'Discord',
'share_feedback' => 'Share feedback',
'last_updates' => 'Last Updates',
'docs' => 'Documentation',
'referral' => 'Earn 30% referral',
'stay_updated' => 'Stay updated',
],
];

View file

@ -388,6 +388,7 @@
],
'status' => [
'pending' => 'Pendiente',
'scheduled' => 'Programado',
'published' => 'Publicado',
'publishing' => 'Publicando...',

View file

@ -24,7 +24,7 @@
'groups' => [
'posts' => 'Posts',
'workspace' => 'Workspace',
'support' => 'Soporte',
'others' => 'Otros',
],
'analytics' => 'Analytics',
@ -54,9 +54,8 @@
'no_notifications' => 'Sin notificaciones',
'support' => [
'discord' => 'Discord',
'share_feedback' => 'Dar feedback',
'last_updates' => 'Últimas actualizaciones',
'docs' => 'Documentación',
'referral' => 'Gana 30% de comisión',
'stay_updated' => 'Mantente al día',
],
];

View file

@ -388,6 +388,7 @@
],
'status' => [
'pending' => 'Pendente',
'scheduled' => 'Agendado',
'published' => 'Publicado',
'publishing' => 'Publicando...',

View file

@ -24,7 +24,7 @@
'groups' => [
'posts' => 'Posts',
'workspace' => 'Workspace',
'support' => 'Suporte',
'others' => 'Outros',
],
'analytics' => 'Analytics',
@ -54,9 +54,8 @@
'no_notifications' => 'Sem notificações',
'support' => [
'discord' => 'Discord',
'share_feedback' => 'Enviar feedback',
'last_updates' => 'Últimas Atualizações',
'docs' => 'Documentação',
'referral' => 'Ganhe 30% de indicação',
'stay_updated' => 'Fique por dentro',
],
];

View file

@ -4,13 +4,16 @@ import {
IconAffiliate,
IconAlertTriangle,
IconBolt,
IconBrandX,
IconCalendar,
IconChartBar,
IconChevronRight,
IconClock,
IconFileCheck,
IconFileText,
IconGift,
IconHash,
IconLifebuoy,
IconPhoto,
IconPencil,
IconPlus,
@ -22,6 +25,7 @@ import { computed } from 'vue';
import { create as createPost, index as postsIndex } from '@/actions/App/Http/Controllers/App/PostController';
import NavMain from '@/components/NavMain.vue';
import NavSupport from '@/components/NavSupport.vue';
import NavUser from '@/components/NavUser.vue';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
@ -43,6 +47,7 @@ import {
SidebarMenuItem,
} from '@/components/ui/sidebar';
import { useActiveUrl } from '@/composables/useActiveUrl';
import { useWorkspaceRole } from '@/composables/useWorkspaceRole';
import { accounts, analytics, calendar, settings as settingsHub } from '@/routes/app';
import { index as assets } from '@/routes/app/assets';
import { index as automations } from '@/routes/app/automations';
@ -63,6 +68,8 @@ const currentWorkspace = computed<Workspace | null>(() => page.props.auth.curren
const workspaces = computed<Workspace[]>(() => page.props.auth.workspaces as Workspace[]);
const subscriptionPastDue = computed<boolean>(() => Boolean(page.props.auth.subscriptionPastDue));
const { canCreatePost, canManageAccounts, canManageAutomations, canCreateWorkspace } = useWorkspaceRole();
const mainNavItems = computed<NavItem[]>(() => [
{
title: trans('sidebar.posts.calendar'),
@ -74,12 +81,16 @@ const mainNavItems = computed<NavItem[]>(() => [
href: analytics.url(),
icon: IconChartBar,
},
{
title: trans('sidebar.automations'),
href: automations.url(),
icon: IconBolt,
badge: 'Beta',
},
...(canManageAutomations.value
? [
{
title: trans('sidebar.automations'),
href: automations.url(),
icon: IconBolt,
badge: 'Beta',
},
]
: []),
]);
const postsNavItems = computed<NavItem[]>(() => [
@ -107,25 +118,51 @@ const postsNavItems = computed<NavItem[]>(() => [
]);
const workspaceNavItems = computed<NavItem[]>(() => [
...(canManageAccounts.value
? [
{
title: trans('sidebar.workspace.connections'),
href: accounts.url(),
icon: IconAffiliate,
},
]
: []),
...(canCreatePost.value
? [
{
title: trans('sidebar.workspace.signatures'),
href: signatures.url(),
icon: IconHash,
},
{
title: trans('sidebar.workspace.labels'),
href: labels.url(),
icon: IconTag,
},
{
title: trans('sidebar.workspace.assets'),
href: assets.url(),
icon: IconPhoto,
},
]
: []),
]);
const supportNavItems = computed(() => [
{
title: trans('sidebar.workspace.connections'),
href: accounts.url(),
icon: IconAffiliate,
title: trans('sidebar.support.referral'),
href: 'https://affiliates.trypost.it/',
icon: IconGift,
},
{
title: trans('sidebar.workspace.signatures'),
href: signatures.url(),
icon: IconHash,
title: trans('sidebar.support.stay_updated'),
href: 'https://x.com/trypostit',
icon: IconBrandX,
},
{
title: trans('sidebar.workspace.labels'),
href: labels.url(),
icon: IconTag,
},
{
title: trans('sidebar.workspace.assets'),
href: assets.url(),
icon: IconPhoto,
title: trans('sidebar.support.docs'),
href: 'https://docs.trypost.it',
icon: IconLifebuoy,
},
]);
@ -176,20 +213,22 @@ const handleCreateWorkspace = () => {
{{ workspace.name }}
</DropdownMenuItem>
</div>
<DropdownMenuSeparator />
<DropdownMenuItem @click="handleCreateWorkspace">
<IconPlus class="size-4" />
{{ $t('sidebar.create_workspace') }}
</DropdownMenuItem>
<template v-if="canCreateWorkspace">
<DropdownMenuSeparator />
<DropdownMenuItem @click="handleCreateWorkspace">
<IconPlus class="size-4" />
{{ $t('sidebar.create_workspace') }}
</DropdownMenuItem>
</template>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<SidebarContent class="gap-px">
<!-- Create Post Button -->
<div v-if="currentWorkspace" class="px-2 py-2">
<div v-if="currentWorkspace && canCreatePost" class="px-2 py-2">
<Link :href="createPost.url()" class="block">
<Button class="w-full">
{{ $t('sidebar.create_post') }}
@ -199,7 +238,8 @@ const handleCreateWorkspace = () => {
<NavMain v-if="currentWorkspace" :items="mainNavItems" />
<NavMain v-if="currentWorkspace" :items="postsNavItems" :label="$t('sidebar.groups.posts')" />
<NavMain v-if="currentWorkspace" :items="workspaceNavItems" :label="$t('sidebar.groups.workspace')" />
<NavMain v-if="currentWorkspace && workspaceNavItems.length" :items="workspaceNavItems" :label="$t('sidebar.groups.workspace')" />
<NavSupport v-if="currentWorkspace" :items="supportNavItems" :label="$t('sidebar.groups.others')" />
</SidebarContent>
<SidebarFooter>

View file

@ -0,0 +1,40 @@
<script setup lang="ts">
import type { Component } from 'vue';
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from '@/components/ui/sidebar';
interface SupportNavItem {
title: string;
icon: Component;
href: string;
}
interface Props {
items: SupportNavItem[];
label?: string;
}
defineProps<Props>();
</script>
<template>
<SidebarGroup class="px-2 py-0">
<SidebarGroupLabel v-if="label">{{ label }}</SidebarGroupLabel>
<SidebarMenu>
<SidebarMenuItem v-for="item in items" :key="item.title">
<SidebarMenuButton as-child :tooltip="item.title">
<a :href="item.href" target="_blank" rel="noopener noreferrer">
<component :is="item.icon" />
<span>{{ item.title }}</span>
</a>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
</template>

View file

@ -2,9 +2,7 @@
import { Link, router, usePage } from '@inertiajs/vue3';
import {
IconLanguage,
IconLifebuoy,
IconLogout,
IconMessageCircle,
IconUser,
} from '@tabler/icons-vue';
import { loadLanguageAsync } from 'laravel-vue-i18n';
@ -106,31 +104,6 @@ const handleLogout = () => {
</DropdownMenuSub>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem :as-child="true">
<a
class="block w-full cursor-pointer"
href="https://github.com/trypost-it/trypost/discussions"
target="_blank"
rel="noopener noreferrer"
>
<IconMessageCircle class="size-4" />
{{ $t('sidebar.support.share_feedback') }}
</a>
</DropdownMenuItem>
<DropdownMenuItem :as-child="true">
<a
class="block w-full cursor-pointer"
href="https://trypost.it/docs"
target="_blank"
rel="noopener noreferrer"
>
<IconLifebuoy class="size-4" />
{{ $t('sidebar.support.docs') }}
</a>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem :as-child="true">
<Link
class="block w-full cursor-pointer"

View file

@ -46,9 +46,11 @@ const props = withDefaults(
platformLimits: PlatformLimit[];
mediaIssues: Record<string, MediaIssue[]>;
allowAiRegenerate?: boolean;
readOnly?: boolean;
}>(),
{
allowAiRegenerate: true,
readOnly: false,
},
);
@ -186,6 +188,7 @@ const onMediaDragEnd = () => {
const GRID_COLS = 4;
const onMediaKeydown = async (event: KeyboardEvent, index: number) => {
if (props.readOnly) return;
if (media.value.length < 2) return;
if (! event.altKey) return;
@ -215,7 +218,7 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
<div class="mx-auto max-w-2xl px-6 py-10">
<div class="relative">
<!-- Media grid (top) — always shown so "Add" tile is discoverable -->
<div class="mb-6">
<div v-if="!readOnly || media.length" class="mb-6">
<div class="grid grid-cols-4 gap-2">
<div
v-for="(item, index) in media"
@ -228,7 +231,7 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
mediaIssues[item.id] ? '!border-rose-500' : '',
]"
tabindex="0"
:draggable="media.length > 1"
:draggable="!readOnly && media.length > 1"
@click="openPreview(item)"
@dragstart="onMediaDragStart($event, index)"
@dragover="onMediaDragOver($event, index)"
@ -289,7 +292,7 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
</TooltipProvider>
<span
v-if="media.length > 1"
v-if="media.length > 1 && !readOnly"
class="absolute left-1.5 top-1.5 inline-flex size-6 cursor-grab items-center justify-center rounded-md border-2 border-foreground bg-card text-foreground opacity-0 shadow-2xs transition-opacity group-hover:opacity-100 group-focus:opacity-100"
>
<IconGripVertical class="size-3.5" />
@ -306,6 +309,7 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
</button>
<button
v-if="!readOnly"
type="button"
class="absolute right-1.5 top-1.5 inline-flex size-6 cursor-pointer items-center justify-center rounded-md border-2 border-foreground bg-card text-foreground opacity-0 shadow-2xs transition-all hover:bg-rose-100 hover:text-rose-700 group-hover:opacity-100 group-focus:opacity-100"
@click.stop="removeMedia(item.id)"
@ -315,6 +319,7 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
</div>
<button
v-if="!readOnly"
type="button"
class="flex aspect-square cursor-pointer flex-col items-center justify-center gap-1 rounded-xl border-2 border-dashed border-foreground/25 text-foreground/60 transition-colors hover:border-foreground hover:bg-foreground/5 hover:text-foreground"
@click="mediaPickerDialog?.open()"
@ -326,7 +331,7 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
</div>
<!-- Toolbar: between photos and textarea -->
<div class="mb-4 flex items-center gap-2">
<div v-if="!readOnly" class="mb-4 flex items-center gap-2">
<Popover v-model:open="emojiOpen">
<PopoverAnchor as-child>
<TooltipProvider>
@ -432,7 +437,8 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
</div>
<textarea
v-model="content"
:placeholder="$t('posts.edit.caption_placeholder')"
:readonly="readOnly"
:placeholder="readOnly ? '' : $t('posts.edit.caption_placeholder')"
class="relative block w-full resize-none border-0 bg-transparent p-0 font-sans text-base leading-[1.7] shadow-none outline-none placeholder:text-foreground/40"
style="min-height: 280px; field-sizing: content;"
/>

View file

@ -11,6 +11,7 @@ import { PostStatus } from '@/types/post';
interface Props {
post: { status: string };
canEdit?: boolean;
isSaving: boolean;
showSaved: boolean;
isSubmitting: boolean;
@ -19,7 +20,9 @@ interface Props {
pickTimeLabel: string;
}
const props = defineProps<Props>();
const props = withDefaults(defineProps<Props>(), {
canEdit: true,
});
const hasPickedTime = defineModel<boolean>('hasPickedTime', { required: true });
const scheduledDateTime = defineModel<string>('scheduledDateTime', { required: true });
@ -61,6 +64,7 @@ const scheduledAtError = computed(() => errors.value.scheduled_at);
</p>
</div>
<Button
v-if="canEdit"
type="button"
variant="outline"
class="bg-background hover:bg-violet-50"
@ -91,7 +95,7 @@ const scheduledAtError = computed(() => errors.value.scheduled_at);
</span>
</div>
<div v-if="!isReadOnly" class="flex flex-col items-end gap-1">
<div v-if="!isReadOnly && canEdit" class="flex flex-col items-end gap-1">
<div class="flex items-center gap-2">
<TooltipProvider>
<Tooltip>

View file

@ -58,6 +58,7 @@ const submit = () => {
:available-fonts="availableFonts"
:available-image-styles="availableImageStyles"
:available-voice-traits="availableVoiceTraits"
:autofill="!workspace.brand_website"
/>
<Button :disabled="form.processing">{{ $t('settings.workspace.save') }}</Button>

View file

@ -22,6 +22,7 @@ import {
TableHeader,
TableRow,
} from '@/components/ui/table';
import { useWorkspaceRole } from '@/composables/useWorkspaceRole';
import { destroy as destroyInvite } from '@/routes/app/invites';
import { remove as removeMemberRoute, updateRole } from '@/routes/app/members';
import { WorkspaceRole } from '@/types/workspace-role';
@ -65,6 +66,8 @@ const roleIcon = (role: string) => {
const page = usePage();
const currentUserId = computed(() => page.props.auth.user.id);
const { canManageTeam } = useWorkspaceRole();
const inviteDialogOpen = ref(false);
const removeMemberModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
const cancelInvitationModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);
@ -86,7 +89,7 @@ const changeRole = (member: Member, role: string) => {
:description="$t('settings.workspace.members_description')"
/>
<Button @click="handleInviteClick">
<Button v-if="canManageTeam" @click="handleInviteClick">
{{ $t('settings.members.invite.submit') }}
</Button>
</div>
@ -110,7 +113,7 @@ const changeRole = (member: Member, role: string) => {
</Badge>
</TableCell>
<TableCell>
<DropdownMenu v-if="member.id !== currentUserId">
<DropdownMenu v-if="canManageTeam && member.id !== currentUserId">
<DropdownMenuTrigger as-child>
<Button variant="outline" size="icon" class="size-8">
<IconDots class="size-4" />
@ -153,6 +156,7 @@ const changeRole = (member: Member, role: string) => {
</TableCell>
<TableCell>
<Button
v-if="canManageTeam"
variant="outline"
size="icon"
class="size-8 bg-rose-100 hover:bg-rose-200"

View file

@ -11,7 +11,7 @@ const props = defineProps<PrimitiveProps & {
<template>
<Primitive data-slot="sidebar-group-label" data-sidebar="group-label" :as="as" :as-child="asChild" :class="cn(
'text-sidebar-foreground/60 ring-sidebar-ring flex h-7 shrink-0 items-center rounded-md px-2 text-[11px] font-black uppercase tracking-widest outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
'text-sidebar-foreground/50 ring-sidebar-ring flex h-7 shrink-0 items-center rounded-md px-2 text-[11px] font-black uppercase tracking-widest outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
'group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0',
props.class)">
<slot />

View file

@ -11,7 +11,7 @@ const props = defineProps<{
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
:class="cn('flex w-full min-w-0 flex-col gap-1', props.class)"
:class="cn('flex w-full min-w-0 flex-col gap-px', props.class)"
>
<slot />
</ul>

View file

@ -0,0 +1,39 @@
import { usePage } from '@inertiajs/vue3';
import { computed } from 'vue';
import { WorkspaceRole } from '@/types/workspace-role';
/**
* Role-based capability flags for the current workspace, mirroring the
* backend `WorkspacePolicy` so UI affordances only render for roles that can
* actually perform the action. Reads `auth.currentWorkspace.role`.
*/
export const useWorkspaceRole = () => {
const page = usePage();
const role = computed<string | null>(
() => (page.props.auth?.currentWorkspace?.role as string | null) ?? null,
);
const isOwner = computed(() => role.value === WorkspaceRole.Owner);
const isAdminOrAbove = computed(
() => isOwner.value || role.value === WorkspaceRole.Admin,
);
const isMemberOrAbove = computed(
() => isAdminOrAbove.value || role.value === WorkspaceRole.Member,
);
return {
role,
isOwner,
isAdminOrAbove,
isMemberOrAbove,
canCreatePost: isMemberOrAbove,
canManageAutomations: isMemberOrAbove,
canManageAccounts: isAdminOrAbove,
canManageTeam: isAdminOrAbove,
canManageWorkspace: isAdminOrAbove,
canManageBilling: isOwner,
canCreateWorkspace: isOwner,
};
};

View file

@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo';
import { useWorkspaceRole } from '@/composables/useWorkspaceRole';
import date from '@/date';
import dayjs from '@/dayjs';
import AppLayout from '@/layouts/AppLayout.vue';
@ -53,6 +54,8 @@ const props = defineProps<Props>();
// Mobile detection
const isMobile = ref(false);
const { canCreatePost } = useWorkspaceRole();
const createPostUrl = (isoDate: string | null = null) =>
isoDate ? createPost.url({ query: { date: isoDate } }) : createPost.url();
const checkMobile = () => {
@ -277,7 +280,7 @@ const formatTime = (scheduledAt: string): string => {
</TabsList>
</Tabs>
<Link :href="createPost.url()">
<Link v-if="canCreatePost" :href="createPost.url()">
<Button>{{ $t('calendar.new_post') }}</Button>
</Link>
</div>
@ -374,6 +377,7 @@ const formatTime = (scheduledAt: string): string => {
<div class="flex-1 space-y-2 overflow-y-auto p-2">
<!-- Add Post Button -->
<Link
v-if="canCreatePost"
:href="createPostUrl(day.format('YYYY-MM-DD'))"
class="flex w-full items-center justify-center rounded-md border-2 border-dashed border-foreground/25 p-2 text-foreground/60 transition-colors hover:border-foreground hover:bg-foreground/5 hover:text-foreground"
>
@ -471,6 +475,7 @@ const formatTime = (scheduledAt: string): string => {
{{ day.format('D') }}
</span>
<Link
v-if="canCreatePost"
:href="createPostUrl(day.format('YYYY-MM-DD'))"
class="inline-flex size-6 items-center justify-center rounded-full border-2 border-foreground bg-card text-foreground opacity-0 shadow-2xs transition-all hover:rotate-90 hover:bg-violet-100 focus:opacity-100 group-hover:opacity-100"
>

View file

@ -17,6 +17,7 @@ import {
getMediaIncompatibilityReason,
usePostCompliance,
} from '@/composables/usePostCompliance';
import { useWorkspaceRole } from '@/composables/useWorkspaceRole';
import date from '@/date';
import dayjs from '@/dayjs';
import debounce from '@/debounce';
@ -90,6 +91,8 @@ const props = defineProps<{
authUserId: string;
}>();
const { canCreatePost } = useWorkspaceRole();
const post = computed(() => props.post);
const READONLY_STATUSES: readonly string[] = [
PostStatus.Publishing,
@ -100,9 +103,7 @@ const READONLY_STATUSES: readonly string[] = [
const isReadOnly = computed(() => READONLY_STATUSES.includes(post.value.status));
const isPublishing = computed(() => post.value.status === PostStatus.Publishing);
const isScheduled = computed(() => post.value.status === PostStatus.Scheduled);
// Locked states — terminal + scheduled. Field edits and auto-save suppressed;
// user must unschedule to re-enter draft and edit.
const isLocked = computed(() => isReadOnly.value || isScheduled.value);
const isLocked = computed(() => isReadOnly.value || isScheduled.value || !canCreatePost.value);
// Content
const content = ref(post.value.content || '');
@ -201,7 +202,10 @@ const isPostActionDisabled = computed(
const queryParams = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
const initialTabFromQuery = (() => {
const tab = queryParams?.get('tab');
return ['preview', 'schedule', 'comments'].includes(tab ?? '') ? (tab as string) : 'schedule';
if (['preview', 'schedule', 'comments'].includes(tab ?? '')) {
return tab as string;
}
return canCreatePost.value ? 'schedule' : 'comments';
})();
const initialHighlightCommentId = queryParams?.get('comment') ?? null;
const activeTab = ref(initialTabFromQuery);
@ -352,6 +356,7 @@ usePostEcho(post.value.id, '.post.comment.created', (e: any) => {
<div class="flex flex-col flex-1 min-h-0">
<PostEditorHeader
:post="post"
:can-edit="canCreatePost"
:is-saving="isSaving"
:show-saved="showSaved"
:is-submitting="isSubmitting"
@ -395,6 +400,7 @@ usePostEcho(post.value.id, '.post.comment.created', (e: any) => {
:platform-limits="platformLimits"
:media-issues="mediaIssues"
:allow-ai-regenerate="!isLocked"
:read-only="!canCreatePost"
@open-ai-generate="isAiGenerateOpen = true"
@open-ai-review="isAiReviewOpen = true"
@open-ai-regenerate-image="onOpenAiRegenerateImage"

View file

@ -33,6 +33,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/comp
import { useWorkspaceEcho } from '@/composables/echo/useWorkspaceEcho';
import { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo';
import { getPostStatusConfig } from '@/composables/usePostStatus';
import { useWorkspaceRole } from '@/composables/useWorkspaceRole';
import dayjs from '@/dayjs';
import debounce from '@/debounce';
import AppLayout from '@/layouts/AppLayout.vue';
@ -142,6 +143,8 @@ const DELETABLE_STATUSES: readonly string[] = [PostStatus.Draft, PostStatus.Sche
const canEdit = (post: Post): boolean => EDITABLE_STATUSES.includes(post.status);
const canDelete = (post: Post): boolean => DELETABLE_STATUSES.includes(post.status);
const { canCreatePost } = useWorkspaceRole();
const postUrl = (post: Post): string =>
canEdit(post) ? editPost.url(post.id) : showPost.url(post.id);
@ -194,7 +197,7 @@ useWorkspaceEcho(
<LabelFilter v-if="labels.length" v-model="selectedLabelIds" :labels="labels" />
</div>
<Link :href="createPost.url()">
<Link v-if="canCreatePost" :href="createPost.url()">
<Button>{{ $t('posts.new_post') }}</Button>
</Link>
</div>
@ -297,7 +300,7 @@ useWorkspaceEcho(
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem @click="handleDuplicate(post)">
<DropdownMenuItem v-if="canCreatePost" @click="handleDuplicate(post)">
<IconCopyPlus class="size-4" />
{{ $t('posts.actions.duplicate') }}
</DropdownMenuItem>
@ -305,7 +308,7 @@ useWorkspaceEcho(
<IconCopy class="size-4" />
{{ $t('posts.actions.copy_id') }}
</DropdownMenuItem>
<template v-if="canDelete(post)">
<template v-if="canCreatePost && canDelete(post)">
<DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"

View file

@ -10,6 +10,7 @@ import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useWorkspaceRole } from '@/composables/useWorkspaceRole';
import AppLayout from '@/layouts/AppLayout.vue';
import { edit as accountEdit, update as accountUpdate } from '@/routes/app/account';
import { index as billingIndex } from '@/routes/app/billing';
@ -26,10 +27,14 @@ defineProps<{
selfHosted: boolean;
}>();
const { canManageBilling } = useWorkspaceRole();
const tabs = computed(() => [
{ name: 'account', label: trans('settings.account.tabs.account'), href: accountEdit().url },
{ name: 'usage', label: trans('settings.account.tabs.usage'), href: usageIndex().url },
{ name: 'billing', label: trans('settings.account.tabs.billing'), href: billingIndex().url },
...(canManageBilling.value
? [{ name: 'billing', label: trans('settings.account.tabs.billing'), href: billingIndex().url }]
: []),
]);
</script>

View file

@ -8,10 +8,9 @@
use App\Models\Workspace;
beforeEach(function () {
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create([
'current_workspace_id' => $this->workspace->id,
]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);
$this->user->refresh();
});

View file

@ -9,8 +9,9 @@
use App\Models\Workspace;
beforeEach(function () {
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create(['current_workspace_id' => $this->workspace->id]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);
$this->user->refresh();
$this->automation = Automation::factory()->for($this->workspace)->create();

View file

@ -25,8 +25,9 @@
beforeEach(function () {
Bus::fake();
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create(['current_workspace_id' => $this->workspace->id]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);
});

View file

@ -9,8 +9,9 @@
use Illuminate\Support\Facades\Http;
beforeEach(function () {
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create(['current_workspace_id' => $this->workspace->id]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);
$this->user->refresh();
});

View file

@ -10,10 +10,9 @@
use App\Models\Workspace;
beforeEach(function () {
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create([
'current_workspace_id' => $this->workspace->id,
]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);
$this->user->refresh();
});

View file

@ -15,8 +15,9 @@
use Illuminate\Support\Facades\Http;
beforeEach(function () {
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create(['current_workspace_id' => $this->workspace->id]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);
$this->user->refresh();
});

View file

@ -8,10 +8,9 @@
use App\Models\Workspace;
beforeEach(function () {
$this->workspace = Workspace::factory()->create();
$this->user = User::factory()->create([
'current_workspace_id' => $this->workspace->id,
]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);
$this->user->refresh();
});

View file

@ -0,0 +1,136 @@
<?php
declare(strict_types=1);
use App\Enums\Post\Status;
use App\Enums\UserWorkspace\Role;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
beforeEach(function () {
$this->owner = User::factory()->create();
$this->workspace = Workspace::factory()->create([
'account_id' => $this->owner->account_id,
'user_id' => $this->owner->id,
]);
$this->owner->update(['current_workspace_id' => $this->workspace->id]);
$this->viewer = User::factory()->create([
'account_id' => $this->owner->account_id,
'current_workspace_id' => $this->workspace->id,
]);
$this->workspace->members()->attach($this->viewer->id, ['role' => Role::Viewer->value]);
$this->member = User::factory()->create([
'account_id' => $this->owner->account_id,
'current_workspace_id' => $this->workspace->id,
]);
$this->workspace->members()->attach($this->member->id, ['role' => Role::Member->value]);
$this->admin = User::factory()->create([
'account_id' => $this->owner->account_id,
'current_workspace_id' => $this->workspace->id,
]);
$this->workspace->members()->attach($this->admin->id, ['role' => Role::Admin->value]);
$this->post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
});
test('a viewer cannot delete a post', function () {
$this->actingAs($this->viewer)
->delete(route('app.posts.destroy', $this->post))
->assertForbidden();
$this->assertDatabaseHas('posts', ['id' => $this->post->id]);
});
test('a viewer cannot create an automation', function () {
$this->actingAs($this->viewer)
->post(route('app.automations.store'))
->assertForbidden();
});
test('a member can create an automation', function () {
$this->actingAs($this->member)
->post(route('app.automations.store'))
->assertRedirect();
});
test('a viewer can comment on a post', function () {
$this->actingAs($this->viewer)
->postJson(route('app.posts.comments.store', $this->post), ['body' => 'Looks good!'])
->assertSuccessful();
$this->assertDatabaseHas('post_comments', [
'post_id' => $this->post->id,
'user_id' => $this->viewer->id,
]);
});
test('opening a draft post redirects to the editor for every workspace member', function (string $actor) {
$this->actingAs($this->{$actor})
->get(route('app.posts.show', $this->post))
->assertRedirect(route('app.posts.edit', $this->post));
})->with(['admin', 'member', 'viewer']);
test('a viewer can open the post editor to review and comment', function () {
$this->actingAs($this->viewer)
->get(route('app.posts.edit', $this->post))
->assertOk();
});
test('a viewer cannot save changes to a post', function () {
$this->actingAs($this->viewer)
->put(route('app.posts.update', $this->post), ['status' => Status::Draft->value])
->assertForbidden();
});
test('only admins and above can open the connections screen', function (string $actor, bool $allowed) {
$response = $this->actingAs($this->{$actor})->get(route('app.accounts'));
$allowed ? $response->assertOk() : $response->assertForbidden();
})->with([
'admin' => ['admin', true],
'member' => ['member', false],
'viewer' => ['viewer', false],
]);
test('opening the editor does not create platform rows for a viewer', function () {
SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'is_active' => true,
]);
$this->actingAs($this->viewer)
->get(route('app.posts.edit', $this->post))
->assertOk();
expect($this->post->postPlatforms()->count())->toBe(0);
});
test('opening the editor syncs platform rows for a member', function () {
SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'is_active' => true,
]);
$this->actingAs($this->member)
->get(route('app.posts.edit', $this->post))
->assertOk();
expect($this->post->postPlatforms()->count())->toBe(1);
});
test('a member without connected accounts is redirected away from the admin-only accounts screen when creating a post', function () {
$this->actingAs($this->member)
->post(route('app.posts.store'))
->assertRedirect(route('app.calendar'));
});
test('an admin without connected accounts is sent to the accounts screen when creating a post', function () {
$this->actingAs($this->admin)
->post(route('app.posts.store'))
->assertRedirect(route('app.accounts'));
});

View file

@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
use App\Models\Account;
use App\Models\Automation;
use App\Models\User;
use App\Models\Workspace;
use App\Policies\AutomationPolicy;
beforeEach(function () {
$this->policy = new AutomationPolicy;
});
/**
* Build an automation + an actor with the given workspace role, both in one account.
*
* @return array{0: User, 1: Automation}
*/
function automationPolicyActor(string $role): array
{
$account = Account::factory()->create();
$owner = User::factory()->create(['account_id' => $account->id]);
$account->update(['owner_id' => $owner->id]);
$workspace = Workspace::factory()->create(['account_id' => $account->id, 'user_id' => $owner->id]);
$automation = Automation::factory()->create(['workspace_id' => $workspace->id]);
if ($role === 'owner') {
$actor = $owner;
} else {
$actor = User::factory()->create(['account_id' => $account->id]);
$workspace->members()->attach($actor->id, ['role' => $role]);
}
$actor->update(['current_workspace_id' => $workspace->id]);
return [$actor->refresh(), $automation];
}
test('any workspace member (including viewer) can view automations', function (string $role) {
[$actor, $automation] = automationPolicyActor($role);
expect($this->policy->viewAny($actor))->toBeTrue()
->and($this->policy->view($actor, $automation))->toBeTrue();
})->with(['owner', 'admin', 'member', 'viewer']);
test('automation create/update/delete/activate/pause is allowed for member+ and denied for viewer', function (string $role, bool $allowed) {
[$actor, $automation] = automationPolicyActor($role);
expect($this->policy->create($actor))->toBe($allowed)
->and($this->policy->update($actor, $automation))->toBe($allowed)
->and($this->policy->delete($actor, $automation))->toBe($allowed)
->and($this->policy->activate($actor, $automation))->toBe($allowed)
->and($this->policy->pause($actor, $automation))->toBe($allowed);
})->with([
'owner' => ['owner', true],
'admin' => ['admin', true],
'member' => ['member', true],
'viewer' => ['viewer', false],
]);

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
use App\Models\Account;
use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
use App\Policies\PostPolicy;
beforeEach(function () {
$this->policy = new PostPolicy;
});
/**
* Build a post + an actor with the given workspace role, both in one account.
*
* @return array{0: User, 1: Post}
*/
function postPolicyActor(string $role): array
{
$account = Account::factory()->create();
$owner = User::factory()->create(['account_id' => $account->id]);
$account->update(['owner_id' => $owner->id]);
$workspace = Workspace::factory()->create(['account_id' => $account->id, 'user_id' => $owner->id]);
$post = Post::factory()->create(['workspace_id' => $workspace->id]);
if ($role === 'owner') {
$actor = $owner;
} else {
$actor = User::factory()->create(['account_id' => $account->id]);
$workspace->members()->attach($actor->id, ['role' => $role]);
}
$actor->update(['current_workspace_id' => $workspace->id]);
return [$actor->refresh(), $post];
}
test('any workspace member (including viewer) can view a post', function (string $role) {
[$actor, $post] = postPolicyActor($role);
expect($this->policy->view($actor, $post))->toBeTrue();
})->with(['owner', 'admin', 'member', 'viewer']);
test('post update/delete/duplicate is allowed for member+ and denied for viewer', function (string $role, bool $allowed) {
[$actor, $post] = postPolicyActor($role);
expect($this->policy->update($actor, $post))->toBe($allowed);
expect($this->policy->delete($actor, $post))->toBe($allowed);
expect($this->policy->duplicate($actor, $post))->toBe($allowed);
})->with([
'owner' => ['owner', true],
'admin' => ['admin', true],
'member' => ['member', true],
'viewer' => ['viewer', false],
]);