Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

init rbac db schema #19

Merged
merged 22 commits into from
Sep 7, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import Link from "next/link";
import { useParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { signOut, useSession } from "next-auth/react";
import { TbCheck, TbChevronDown } from "react-icons/tb";

import { Button } from "@ctrlplane/ui/button";
Expand Down Expand Up @@ -80,7 +80,7 @@ export const SidebarWorkspaceDropdown: React.FC = () => {
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
<DropdownMenuItem>Log out</DropdownMenuItem>
<DropdownMenuItem onClick={() => signOut()}>Log out</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ export const CreateReleaseDialog: React.FC<{
{ workspaceId: workspace.data?.id ?? "" },
{ enabled: workspace.isSuccess },
);
const deployments = api.deployment.bySystemId.useQuery(systemId);
const deployments = api.deployment.bySystemId.useQuery(systemId, {
enabled: systemId !== "",
});
const globalDeployments = api.deployment.byWorkspaceId.useQuery(
workspace.data?.id ?? "",
{ enabled: workspace.data != null },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,13 @@ export const CreateSystemDialog: React.FC<{
const router = useRouter();
const utils = api.useUtils();
const onSubmit = form.handleSubmit(async (values) => {
const system = await create.mutateAsync({ workspaceId, ...values });
await utils.system.list.invalidate();
router.push(`/${workspaceSlug}/systems/${system.slug}`);
try {
const system = await create.mutateAsync({ workspaceId, ...values });
await utils.system.list.invalidate();
router.push(`/${workspaceSlug}/systems/${system.slug}`);
} catch (e) {
console.error(e);
}
Comment on lines +55 to +61
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will handle this with the slug validation once my other PR looks good.

setOpen(false);
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
"use client";

import type { User, WorkspaceMember } from "@ctrlplane/db/schema";
import type { Role, User, Workspace } from "@ctrlplane/db/schema";
import type { ColumnDef, ColumnFiltersState } from "@tanstack/react-table";
import { useState } from "react";
import { useMemo, useState } from "react";
import {
flexRender,
getCoreRowModel,
getFilteredRowModel,
useReactTable,
} from "@tanstack/react-table";
import { capitalCase } from "change-case";
import { TbCheck, TbChevronDown, TbCopy, TbDots } from "react-icons/tb";
import { TbCheck, TbCopy, TbDots } from "react-icons/tb";
import { useCopyToClipboard } from "react-use";
import { v4 } from "uuid";

import { Avatar, AvatarFallback, AvatarImage } from "@ctrlplane/ui/avatar";
Expand All @@ -30,44 +30,56 @@ import {
DropdownMenuTrigger,
} from "@ctrlplane/ui/dropdown-menu";
import { Input } from "@ctrlplane/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@ctrlplane/ui/select";
import { Table, TableBody, TableCell, TableRow } from "@ctrlplane/ui/table";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@ctrlplane/ui/tooltip";
import { predefinedRoles } from "@ctrlplane/validators/auth";

import { api } from "~/trpc/react";

interface Member {
type Member = {
id: string;
user: User;
workspace_member: WorkspaceMember;
}
workspace: Workspace;
role: Role;
};

const InviteLinkSection: React.FC<{
sessionMember?: Member;
workspaceSlug: string;
workspace: Workspace;
inviteLink?: string;
}> = ({ sessionMember, workspaceSlug, inviteLink }) => {
const workspace = api.workspace.bySlug.useQuery(workspaceSlug);
const utils = api.useUtils();
const { mutateAsync } = api.invite.workspace.link.create.useMutation({
onSuccess: () =>
utils.invite.workspace.link.byWorkspaceMemberId.invalidate(),
});
}> = ({ workspace, inviteLink }) => {
const create = api.workspace.invite.token.create.useMutation();

const [, copy] = useCopyToClipboard();
const [clickedCopy, setClickedCopy] = useState(false);
const [roleId, setRoleId] = useState(predefinedRoles.admin.id);

const [token] = useState(inviteLink ?? v4());
const token = useMemo(() => inviteLink ?? v4(), [inviteLink]);
const baseUrl = api.runtime.baseUrl.useQuery();
const link = `${baseUrl.data}/join/${token}`;

const roles = api.workspace.roles.useQuery(workspace.id);

const handleCopyClick = () => {
navigator.clipboard.writeText(link).then(() => {
setClickedCopy(true);
setTimeout(() => setClickedCopy(false), 1000);
copy(link);
setClickedCopy(true);
setTimeout(() => setClickedCopy(false), 1000);
create.mutate({
roleId,
workspaceId: workspace.id,
token,
});

if (inviteLink == null && workspace.data != null && sessionMember != null)
mutateAsync({
workspaceId: workspace.data.id,
workspaceMemberId: sessionMember.workspace_member.id,
token,
});
};

return (
Expand All @@ -79,6 +91,19 @@ const InviteLinkSection: React.FC<{
</p>
</div>

<Select value={roleId} onValueChange={setRoleId}>
<SelectTrigger className="w-[200px]">
<SelectValue placeholder="Select a role" />
</SelectTrigger>
<SelectContent className="w-[200px]">
Comment on lines +95 to +98
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

w-48 | width: 12rem; /* 192px */
w-52 | width: 13rem; /* 208px */

{roles.data?.map((r) => (
<SelectItem key={r.id} value={r.id}>
{r.name}
</SelectItem>
))}
</SelectContent>
</Select>

<div className="flex items-center space-x-2">
<Input readOnly value={link} className="w-96 overflow-ellipsis" />
<Button variant="outline" size="icon" onClick={handleCopyClick}>
Expand All @@ -90,14 +115,9 @@ const InviteLinkSection: React.FC<{
};

const AddMembersDialog: React.FC<{
workspaceSlug: string;
sessionMember?: Member;
}> = ({ sessionMember, workspaceSlug }) => {
const [inviteMode, setInviteMode] = useState<"email" | "link">("email");
const inviteLink = api.invite.workspace.link.byWorkspaceMemberId.useQuery(
sessionMember?.workspace_member.id ?? "",
{ enabled: sessionMember != null },
);
workspace: Workspace;
}> = ({ workspace }) => {
const [inviteMode, setInviteMode] = useState<"email" | "link">("link");

return (
<Dialog>
Expand All @@ -106,15 +126,11 @@ const AddMembersDialog: React.FC<{
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Invite to {capitalCase(workspaceSlug)}</DialogTitle>
<DialogTitle>Invite to {workspace.name}</DialogTitle>
</DialogHeader>

{inviteMode === "link" ? (
<InviteLinkSection
sessionMember={sessionMember}
workspaceSlug={workspaceSlug}
inviteLink={inviteLink.data?.token}
/>
<InviteLinkSection workspace={workspace} />
) : (
<div>email</div>
)}
Expand Down Expand Up @@ -169,36 +185,64 @@ const columns: ColumnDef<Member>[] = [
{
id: "role",
header: "Role",
accessorKey: "workspace_member.role",
accessorKey: "role",
enableGlobalFilter: false,
cell: "admin",
cell: ({ row }) => {
const { id: currentRoleId } = row.original.role;
const roles = api.workspace.roles.useQuery(row.original.workspace.id);

return (
<Select defaultValue={currentRoleId}>
<SelectTrigger className="w-[230px]">
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

w-56 | width: 14rem; /* 224px */
w-60 | width: 15rem; /* 240px */

<SelectValue placeholder="Select a role" />
</SelectTrigger>
<SelectContent>
{roles.data?.map((role) => (
<SelectItem key={role.id} value={role.id}>
<TooltipProvider>
<Tooltip>
<TooltipTrigger>{role.name}</TooltipTrigger>
{role.description && (
<TooltipContent>
<p>{role.description}</p>
</TooltipContent>
)}
</Tooltip>
</TooltipProvider>
</SelectItem>
))}
</SelectContent>
</Select>
);
},
},
{
id: "actions",
header: "Actions",
accessorKey: "user.id",
enableGlobalFilter: false,
cell: () => (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<TbDots />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>Edit</DropdownMenuItem>
<DropdownMenuItem>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<div className="flex justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon">
<TbDots />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem>Edit</DropdownMenuItem>
<DropdownMenuItem>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
),
},
];

export const MembersTable: React.FC<{
workspaceSlug: string;
workspace: Workspace;
data: Array<Member>;
sessionMember?: Member;
}> = ({ workspaceSlug, data, sessionMember }) => {
}> = ({ workspace, data }) => {
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);

const table = useReactTable({
Expand All @@ -224,30 +268,15 @@ export const MembersTable: React.FC<{
className="w-72"
onChange={(e) => table.setGlobalFilter(e.target.value)}
/>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" className="flex items-center gap-1">
<TbChevronDown />
Filter
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuItem>Admins</DropdownMenuItem>
<DropdownMenuItem>Members</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<AddMembersDialog
workspaceSlug={workspaceSlug}
sessionMember={sessionMember}
/>
<AddMembersDialog workspace={workspace} />
</div>
<Table>
<TableBody>
{table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
className="flex items-center justify-between border-b-neutral-800/50 px-0 hover:bg-transparent"
className="border-b-neutral-800/50 px-0 hover:bg-transparent"
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
"use client";

import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { useSession } from "next-auth/react";
import { TbArrowRight } from "react-icons/tb";

import { auth } from "@ctrlplane/auth";
import { Button } from "@ctrlplane/ui/button";

import { api } from "~/trpc/react";
import { api } from "~/trpc/server";
import { MembersTable } from "./WorkspaceMembersTable";

export default function WorkspaceSettingMembersPage({
export const metadata: Metadata = { title: "Workspace Members" };

export default async function WorkspaceSettingMembersPage({
params,
}: {
params: { workspaceSlug: string };
}) {
const session = useSession();
const session = await auth();
if (session == null) notFound();

const { workspaceSlug } = params;
const workspace = api.workspace.bySlug.useQuery(workspaceSlug);
const members = api.workspace.members.list.useQuery(
workspace.data?.id ?? "",
{ enabled: workspace.isSuccess },
);
const sessionMember = members.data?.find(
(m) => m.user.id === session.data?.user.id,
);
const workspace = await api.workspace.bySlug(workspaceSlug);
if (workspace == null) return notFound();

if (!workspace.isLoading && workspace.data == null) return notFound();
const members = await api.workspace.members.list(workspace.id);

return (
<div className="container mx-auto max-w-2xl space-y-8">
Expand All @@ -37,21 +33,9 @@ export default function WorkspaceSettingMembersPage({
</div>
<div className="border-b" />
<div className="space-y-1">
<p className="font-semibold">Manage members</p>
<p className="text-sm text-muted-foreground">
On the Free plan all members in a workspace are administrators.
Upgrade to a paid plan to add the ability to assign or remove
administrator roles.{" "}
<span className="inline-flex items-center text-blue-600">
Go to Plans <TbArrowRight />
</span>
</p>
<p className="font-semibold">Manage members ({members.length})</p>
</div>
<MembersTable
data={members.data ?? []}
workspaceSlug={workspaceSlug}
sessionMember={sessionMember}
/>
<MembersTable data={members} workspace={workspace} />
<div className="border-b" />
<div className="flex items-center">
<div className="flex-grow">
Expand Down
Loading
Loading