Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

edit role feature, limit RBAC to enterprise only

Steven Tey951c4c3d5c11
diff --git a/app/ui/form.tsx b/app/ui/form.tsx
index 82a63e4346..57d676a3bf 100644
--- a/app/ui/form.tsx
+++ b/app/ui/form.tsx
@@ -1,17 +1,20 @@
-import { useState, useMemo, InputHTMLAttributes } from "react";
+import { useState, useMemo, InputHTMLAttributes, ReactNode } from "react";
import Button from "#/ui/button";
+import { cn } from "#/lib/utils";
export default function Form({
title,
description,
inputData,
helpText,
+ disabledTooltip,
handleSubmit,
}: {
title: string;
description: string;
inputData: InputHTMLAttributes<HTMLInputElement>;
helpText?: string;
+ disabledTooltip?: string | ReactNode;
handleSubmit: (data) => Promise<any>;
}) {
const [value, setValue] = useState(inputData.defaultValue);
@@ -42,8 +45,14 @@ export default function Form({
{...inputData}
type="text"
required
+ disabled={disabledTooltip ? true : false}
onChange={(e) => setValue(e.target.value)}
- className="w-full max-w-md rounded-md border border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ className={cn(
+ "w-full max-w-md rounded-md border border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm",
+ {
+ "cursor-not-allowed bg-gray-100 text-gray-400": disabledTooltip,
+ },
+ )}
/>
) : (
<div className="h-[2.35rem] w-full max-w-md animate-pulse rounded-md bg-gray-200" />
@@ -57,6 +66,7 @@ export default function Form({
text="Save Changes"
loading={saving}
disabled={saveDisabled}
+ disabledTooltip={disabledTooltip}
/>
</div>
</div>
diff --git a/components/app/modals/delete-project-modal.tsx b/components/app/modals/delete-project-modal.tsx
index 45fca55fd9..205f2ad5e8 100644
--- a/components/app/modals/delete-project-modal.tsx
+++ b/components/app/modals/delete-project-modal.tsx
@@ -23,9 +23,8 @@ function DeleteProjectModal({
}) {
const router = useRouter();
const { slug } = router.query as { slug: string };
- const { id, logo, isOwner } = useProject();
+ const { id, logo, plan, isOwner } = useProject();
- console.log({ isOwner });
const [deleting, setDeleting] = useState(false);
async function deleteProject() {
@@ -103,11 +102,12 @@ function DeleteProjectModal({
autoFocus={false}
autoComplete="off"
pattern={slug}
- disabled={!isOwner}
+ disabled={plan === "enterprise" && !isOwner}
className={cn(
"block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm",
{
- "cursor-not-allowed bg-gray-100": !isOwner,
+ "cursor-not-allowed bg-gray-100":
+ plan === "enterprise" && !isOwner,
},
)}
/>
@@ -131,11 +131,12 @@ function DeleteProjectModal({
required
autoFocus={false}
autoComplete="off"
- disabled={!isOwner}
+ disabled={plan === "enterprise" && !isOwner}
className={cn(
"block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm",
{
- "cursor-not-allowed bg-gray-100": !isOwner,
+ "cursor-not-allowed bg-gray-100":
+ plan === "enterprise" && !isOwner,
},
)}
/>
@@ -146,9 +147,10 @@ function DeleteProjectModal({
text="Confirm delete project"
variant="danger"
loading={deleting}
- {...(!isOwner && {
- disabledTooltip: "Only project owners can delete a project.",
- })}
+ {...(plan === "enterprise" &&
+ !isOwner && {
+ disabledTooltip: "Only project owners can delete a project.",
+ })}
/>
</form>
</Modal>
diff --git a/components/app/modals/edit-role-modal.tsx b/components/app/modals/edit-role-modal.tsx
new file mode 100644
index 0000000000..aa826851da
--- /dev/null
+++ b/components/app/modals/edit-role-modal.tsx
@@ -0,0 +1,132 @@
+import { useRouter } from "next/router";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { mutate } from "swr";
+import BlurImage from "#/ui/blur-image";
+import Modal from "#/ui/modal";
+import useProject from "#/lib/swr/use-project";
+import { toast } from "sonner";
+import Button from "#/ui/button";
+import { UserProps } from "#/lib/types";
+import { Logo } from "#/ui/icons";
+import { useSession } from "next-auth/react";
+
+function EditRoleModal({
+ showEditRoleModal,
+ setShowEditRoleModal,
+ user,
+ role,
+}: {
+ showEditRoleModal: boolean;
+ setShowEditRoleModal: Dispatch<SetStateAction<boolean>>;
+ user: UserProps;
+ role: "owner" | "member";
+}) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+ const [editing, setEditing] = useState(false);
+ const { name: projectName, logo } = useProject();
+ const { id, name, email, image } = user;
+
+ return (
+ <Modal showModal={showEditRoleModal} setShowModal={setShowEditRoleModal}>
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 sm:px-16">
+ {logo ? (
+ <BlurImage
+ src={logo}
+ alt="Project logo"
+ className="h-10 w-10 rounded-full"
+ width={20}
+ height={20}
+ />
+ ) : (
+ <Logo />
+ )}
+ <h3 className="text-lg font-medium">Change Teammate Role</h3>
+ <p className="text-center text-sm text-gray-500">
+ This will change <b className="text-gray-800">{name || email}</b>'s
+ role in <b className="text-gray-800">{projectName}</b> to{" "}
+ <b className="text-gray-800">{role}</b>. Are you sure you want to
+ continue?
+ </p>
+ </div>
+
+ <div className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 text-left sm:px-16">
+ <div className="flex items-center space-x-3 rounded-md border border-gray-300 bg-white p-3">
+ <BlurImage
+ src={image || `https://avatars.dicebear.com/api/micah/${email}.svg`}
+ alt={email}
+ width={40}
+ height={40}
+ className="overflow-hidden rounded-full border border-gray-200"
+ />
+ <div className="flex flex-col">
+ <h3 className="text-sm font-medium">{name || email}</h3>
+ <p className="text-xs text-gray-500">{email}</p>
+ </div>
+ </div>
+ <Button
+ text="Confirm"
+ loading={editing}
+ onClick={() => {
+ setEditing(true);
+ fetch(`/api/projects/${slug}/users`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ userId: id,
+ role,
+ }),
+ }).then(async (res) => {
+ setEditing(false);
+ if (res.status === 200) {
+ toast.success(
+ `Successfully changed ${name || email}'s role to ${role}.`,
+ );
+ mutate(`/api/projects/${slug}/users`);
+ setShowEditRoleModal(false);
+ } else {
+ const error = await res.text();
+ toast.error(error);
+ }
+ });
+ }}
+ />
+ </div>
+ </Modal>
+ );
+}
+
+export function useEditRoleModal({
+ user,
+ role,
+}: {
+ user: UserProps;
+ role: "owner" | "member";
+}) {
+ const [showEditRoleModal, setShowEditRoleModal] = useState(false);
+
+ const EditRoleModalCallback = useCallback(() => {
+ return (
+ <EditRoleModal
+ showEditRoleModal={showEditRoleModal}
+ setShowEditRoleModal={setShowEditRoleModal}
+ user={user}
+ role={role}
+ />
+ );
+ }, [showEditRoleModal, setShowEditRoleModal]);
+
+ return useMemo(
+ () => ({
+ setShowEditRoleModal,
+ EditRoleModal: EditRoleModalCallback,
+ }),
+ [setShowEditRoleModal, EditRoleModalCallback],
+ );
+}
diff --git a/components/app/modals/remove-saml-modal.tsx b/components/app/modals/remove-saml-modal.tsx
index 244e2fbc3e..e66b598b22 100644
--- a/components/app/modals/remove-saml-modal.tsx
+++ b/components/app/modals/remove-saml-modal.tsx
@@ -88,7 +88,8 @@ function RemoveSAMLModal({
setRemoving(false);
setShowRemoveSAMLModal(false);
} else {
- toast.error("Error removing SAML");
+ const error = await res.text();
+ toast.error(error);
setRemoving(false);
}
});
diff --git a/components/app/modals/remove-scim-modal.tsx b/components/app/modals/remove-scim-modal.tsx
index 0972f9efe3..caf3eeddac 100644
--- a/components/app/modals/remove-scim-modal.tsx
+++ b/components/app/modals/remove-scim-modal.tsx
@@ -93,7 +93,8 @@ function RemoveSCIMModal({
setRemoving(false);
setShowRemoveSCIMModal(false);
} else {
- toast.error("Error removing SCIM directory");
+ const error = await res.text();
+ toast.error(error);
setRemoving(false);
}
});
diff --git a/components/app/projects/delete-project.tsx b/components/app/projects/delete-project.tsx
index 83945b8f49..85635e8d8c 100644
--- a/components/app/projects/delete-project.tsx
+++ b/components/app/projects/delete-project.tsx
@@ -7,11 +7,11 @@ export default function DeleteProject() {
const { setShowDeleteProjectModal, DeleteProjectModal } =
useDeleteProjectModal();
- const { isOwner } = useProject();
+ const { plan, isOwner } = useProject();
return (
<div
className={cn("rounded-lg border border-red-600 bg-white", {
- "border-gray-200": !isOwner,
+ "border-gray-200": plan === "enterprise" && !isOwner,
})}
>
<DeleteProjectModal />
@@ -25,7 +25,7 @@ export default function DeleteProject() {
</div>
<div
className={cn("border-b border-red-600", {
- "border-gray-200": !isOwner,
+ "border-gray-200": plan === "enterprise" && !isOwner,
})}
/>
@@ -35,9 +35,10 @@ export default function DeleteProject() {
text="Delete Project"
variant="danger"
onClick={() => setShowDeleteProjectModal(true)}
- {...(!isOwner && {
- disabledTooltip: "Only project owners can delete a project.",
- })}
+ {...(plan === "enterprise" &&
+ !isOwner && {
+ disabledTooltip: "Only project owners can delete a project.",
+ })}
/>
</div>
</div>
diff --git a/lib/auth.ts b/lib/auth.ts
index 26b6e65ec0..bb44c127c8 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -115,7 +115,10 @@ const withProjectAuth =
return handler(req, res, project, session);
}
- if (!requiredRole.includes(project.users[0].role)) {
+ if (
+ project.plan === "enterprise" &&
+ !requiredRole.includes(project.users[0].role)
+ ) {
return res.status(403).end("Unauthorized: Insufficient permissions.");
}
diff --git a/lib/types.ts b/lib/types.ts
index 9dce45d1a9..f6bf6a5130 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -81,8 +81,7 @@ export interface UserProps {
email: string;
image?: string;
createdAt: Date;
-
- joinedAt?: Date;
+ role: "owner" | "member";
projects?: { projectId: string }[];
}
diff --git a/pages/api/projects/[slug]/invites/index.tsx b/pages/api/projects/[slug]/invites/index.tsx
index 0d4969837c..ff446ce14b 100644
--- a/pages/api/projects/[slug]/invites/index.tsx
+++ b/pages/api/projects/[slug]/invites/index.tsx
@@ -14,12 +14,7 @@ export default withProjectAuth(async (req, res, project, session) => {
createdAt: true,
},
});
- return res.status(200).json(
- invites.map((invite) => ({
- email: invite.email,
- joinedAt: invite.createdAt,
- })),
- );
+ return res.status(200).json(invites);
// POST /api/projects/[slug]/invites – invite a teammate
} else if (req.method === "POST") {
diff --git a/pages/api/projects/[slug]/users.ts b/pages/api/projects/[slug]/users.ts
index 9567536abb..b8a2d36f46 100644
--- a/pages/api/projects/[slug]/users.ts
+++ b/pages/api/projects/[slug]/users.ts
@@ -1,69 +1,97 @@
import { withProjectAuth } from "#/lib/auth";
import prisma from "#/lib/prisma";
-export default withProjectAuth(async (req, res, project) => {
- // GET /api/projects/[slug]/users – get users for a specific project
- if (req.method === "GET") {
- const users = await prisma.projectUsers.findMany({
- where: {
- projectId: project.id,
- },
- select: {
- user: {
- select: {
- id: true,
- name: true,
- email: true,
- image: true,
+export default withProjectAuth(
+ async (req, res, project) => {
+ // GET /api/projects/[slug]/users – get users for a specific project
+ if (req.method === "GET") {
+ const users = await prisma.projectUsers.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ role: true,
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ image: true,
+ },
},
+ createdAt: true,
},
- createdAt: true,
- },
- });
- return res.status(200).json(
- users.map((u) => ({
- ...u.user,
- joinedAt: u.createdAt,
- })),
- );
- } else if (req.method === "DELETE") {
- // DELETE /api/projects/[slug]/users – remove a user from a project
- const { userId } = req.query as { userId?: string };
- if (!userId) {
- return res.status(400).end("Missing userId");
- }
+ });
+ return res.status(200).json(
+ users.map((u) => ({
+ ...u.user,
+ role: u.role,
+ })),
+ );
+ } else if (req.method === "PUT") {
+ const { userId, role } = req.body as {
+ userId?: string;
+ role?: "owner" | "member";
+ };
+ if (!userId || !role) {
+ return res.status(400).end("Missing userId or role");
+ }
+ const response = await prisma.projectUsers.update({
+ where: {
+ userId_projectId: {
+ projectId: project.id,
+ userId,
+ },
+ },
+ data: {
+ role,
+ },
+ });
- const projectUser = await prisma.projectUsers.findUnique({
- where: {
- userId_projectId: {
- projectId: project.id,
- userId,
+ return res.status(200).json(response);
+ } else if (req.method === "DELETE") {
+ // DELETE /api/projects/[slug]/users – remove a user from a project
+ const { userId } = req.query as { userId?: string };
+ if (!userId) {
+ return res.status(400).end("Missing userId");
+ }
+
+ const projectUser = await prisma.projectUsers.findUnique({
+ where: {
+ userId_projectId: {
+ projectId: project.id,
+ userId,
+ },
},
- },
- select: {
- role: true,
- },
- });
+ select: {
+ role: true,
+ },
+ });
- if (projectUser?.role === "owner") {
- return res
- .status(400)
- .end(
- "Cannot remove owner from project. Please transfer ownership to another user first.",
- );
- }
+ if (projectUser?.role === "owner") {
+ return res
+ .status(400)
+ .end(
+ "Cannot remove owner from project. Please transfer ownership to another user first.",
+ );
+ }
- const response = await prisma.projectUsers.delete({
- where: {
- userId_projectId: {
- projectId: project.id,
- userId,
+ const response = await prisma.projectUsers.delete({
+ where: {
+ userId_projectId: {
+ projectId: project.id,
+ userId,
+ },
},
- },
- });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-});
+ });
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+ },
+ {
+ requiredRole: ["owner"],
+ excludeGet: true,
+ },
+);
diff --git a/pages/app/[slug]/settings/index.tsx b/pages/app/[slug]/settings/index.tsx
index 9bf7130fdb..b5d118f62b 100644
--- a/pages/app/[slug]/settings/index.tsx
+++ b/pages/app/[slug]/settings/index.tsx
@@ -9,7 +9,7 @@ import UploadLogo from "@/components/app/projects/upload-logo";
export default function ProjectSettingsGeneral() {
const router = useRouter();
- const { name, slug } = useProject();
+ const { name, slug, plan, isOwner } = useProject();
return (
<SettingsLayout>
@@ -23,6 +23,10 @@ export default function ProjectSettingsGeneral() {
maxLength: 32,
}}
helpText="Max 32 characters."
+ {...(plan === "enterprise" &&
+ !isOwner && {
+ disabledTooltip: "Only project owners can change the project name.",
+ })}
handleSubmit={(updateData) =>
fetch(`/api/projects/${slug}`, {
method: "PUT",
@@ -55,6 +59,10 @@ export default function ProjectSettingsGeneral() {
maxLength: 48,
}}
helpText="Only lowercase letters, numbers, and dashes. Max 48 characters."
+ {...(plan === "enterprise" &&
+ !isOwner && {
+ disabledTooltip: "Only project owners can change the project slug.",
+ })}
handleSubmit={(data) =>
fetch(`/api/projects/${slug}`, {
method: "PUT",
diff --git a/pages/app/[slug]/settings/people.tsx b/pages/app/[slug]/settings/people.tsx
index aafc0c8ad5..f726430c3e 100644
--- a/pages/app/[slug]/settings/people.tsx
+++ b/pages/app/[slug]/settings/people.tsx
@@ -3,7 +3,7 @@ import { useInviteTeammateModal } from "components/app/modals/invite-teammate-mo
import { useState } from "react";
import BlurImage from "#/ui/blur-image";
import { UserProps } from "#/lib/types";
-import { timeAgo } from "#/lib/utils";
+import { cn, timeAgo } from "#/lib/utils";
import Popover from "#/ui/popover";
import IconMenu from "@/components/shared/icon-menu";
import { UserMinus } from "lucide-react";
@@ -12,6 +12,8 @@ import { useRemoveTeammateModal } from "@/components/app/modals/remove-teammate-
import Badge from "#/ui/badge";
import useUsers from "#/lib/swr/use-users";
import { useSession } from "next-auth/react";
+import { useEditRoleModal } from "@/components/app/modals/edit-role-modal";
+import useProject from "#/lib/swr/use-project";
const tabs: Array<"Members" | "Invitations"> = ["Members", "Invitations"];
@@ -99,21 +101,32 @@ const UserCard = ({
currentTab: "Members" | "Invitations";
}) => {
const [openPopover, setOpenPopover] = useState(false);
+
+ const { plan, isOwner } = useProject();
+
+ const { name, email, image, createdAt, role: currentRole } = user;
+
+ const [role, setRole] = useState<"owner" | "member">(currentRole);
+
+ const { EditRoleModal, setShowEditRoleModal } = useEditRoleModal({
+ user,
+ role,
+ });
+
const { RemoveTeammateModal, setShowRemoveTeammateModal } =
useRemoveTeammateModal({ user, invite: currentTab === "Invitations" });
- const { name, email, image, joinedAt } = user;
-
const { data: session } = useSession();
// invites expire after 14 days of being sent
const expiredInvite =
currentTab === "Invitations" &&
- joinedAt &&
- Date.now() - new Date(joinedAt).getTime() > 14 * 24 * 60 * 60 * 1000;
+ createdAt &&
+ Date.now() - new Date(createdAt).getTime() > 14 * 24 * 60 * 60 * 1000;
return (
<>
+ <EditRoleModal />
<RemoveTeammateModal />
<div
key={email}
@@ -139,10 +152,35 @@ const UserCard = ({
{expiredInvite && <Badge variant="gray" text="Expired" />}
</div>
<div className="flex items-center space-x-3">
- <p className="text-xs text-gray-500">
- {currentTab === "Members" ? "Joined " : "Invited "}
- {timeAgo(joinedAt)}
- </p>
+ {currentTab === "Members" ? (
+ session?.user?.email === email ? (
+ <p className="text-xs capitalize text-gray-500">{role}</p>
+ ) : (
+ <select
+ className={cn(
+ "rounded-md border border-gray-200 text-xs text-gray-500 focus:border-gray-600 focus:ring-gray-600",
+ {
+ "cursor-not-allowed bg-gray-100":
+ plan === "enterprise" && !isOwner,
+ },
+ )}
+ value={role}
+ disabled={plan === "enterprise" && !isOwner}
+ onChange={(e) => {
+ setRole(e.target.value as "owner" | "member");
+ setOpenPopover(false);
+ setShowEditRoleModal(true);
+ }}
+ >
+ <option value="owner">Owner</option>
+ <option value="member">Member</option>
+ </select>
+ )
+ ) : (
+ <p className="text-xs text-gray-500">
+ `Invited ${timeAgo(createdAt)}`
+ </p>
+ )}
<Popover
content={
diff --git a/pages/app/[slug]/settings/security.tsx b/pages/app/[slug]/settings/security.tsx
index cd3e7258a1..8d711c4e59 100644
--- a/pages/app/[slug]/settings/security.tsx
+++ b/pages/app/[slug]/settings/security.tsx
@@ -34,7 +34,7 @@ const SAMLSection = ({
}: {
setShowUpgradePlanModal: Dispatch<SetStateAction<boolean>>;
}) => {
- const { plan } = useProject();
+ const { plan, isOwner } = useProject();
const { SAMLModal, setShowSAMLModal } = useSAMLModal();
const { RemoveSAMLModal, setShowRemoveSAMLModal } = useRemoveSAMLModal();
const { provider, configured, loading } = useSAML();