Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

added user setting page

Ashish Viradiyac9b7aa84a1c7
diff --git a/app/(auth)/auth/confirm-email-change/page-client.tsx b/app/(auth)/auth/confirm-email-change/page-client.tsx
new file mode 100644
index 00000000..cdbeddba
--- /dev/null
+++ b/app/(auth)/auth/confirm-email-change/page-client.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+
+import { useEffect, useRef } from "react";
+
+import { useSession } from "next-auth/react";
+import { toast } from "sonner";
+
+import LoadingSpinner from "@/components/ui/loading-spinner";
+
+export default function ConfirmEmailChangePageClient() {
+ const router = useRouter();
+ const { update, status } = useSession();
+ const hasUpdatedSession = useRef(false);
+
+ useEffect(() => {
+ if (status !== "authenticated" || hasUpdatedSession.current) {
+ return;
+ }
+
+ async function updateSession() {
+ hasUpdatedSession.current = true;
+ await update();
+ router.replace("/account/general");
+ toast.success("Email update successful!");
+ }
+
+ updateSession();
+ }, [status, update, router]);
+
+ return (
+ <div className="flex h-screen w-full items-center justify-center">
+ <LoadingSpinner className="h-20 w-20 text-foreground" />
+ </div>
+ );
+}
diff --git a/app/(auth)/auth/confirm-email-change/page.tsx b/app/(auth)/auth/confirm-email-change/page.tsx
new file mode 100644
index 00000000..ca05ca6d
--- /dev/null
+++ b/app/(auth)/auth/confirm-email-change/page.tsx
@@ -0,0 +1,98 @@
+import { redirect } from "next/navigation";
+
+import NotFound from "@/pages/404";
+import { waitUntil } from "@vercel/functions";
+
+import EmailUpdated from "@/components/emails/email-updated";
+
+import { hashToken } from "@/lib/api/auth/token";
+import prisma from "@/lib/prisma";
+import { sendEmail } from "@/lib/resend";
+import { CustomUser } from "@/lib/types";
+import { generateChecksum } from "@/lib/utils/generate-checksum";
+
+import ConfirmEmailChangePageClient from "./page-client";
+import { getSession } from "./utils";
+
+export const runtime = "nodejs";
+
+interface ConfirmEmailChangePageProps {
+ searchParams: {
+ verification_url: string;
+ checksum: string;
+ email: string;
+ newEmail: string;
+ };
+}
+
+export default async function ConfirmEmailChangePage(
+ props: ConfirmEmailChangePageProps,
+) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-6 text-center">
+ <VerifyEmailChange {...props} />
+ </div>
+ );
+}
+
+const VerifyEmailChange = async ({
+ searchParams: { checksum, verification_url, email, newEmail },
+}: ConfirmEmailChangePageProps) => {
+ const urlObj = new URL(verification_url);
+
+ const isValidVerificationUrl = (url: string, checksum: string): boolean => {
+ try {
+ if (urlObj.origin !== process.env.NEXTAUTH_URL) return false;
+ const expectedChecksum = generateChecksum(url);
+ return checksum === expectedChecksum;
+ } catch {
+ return false;
+ }
+ };
+
+ if (!isValidVerificationUrl(verification_url, checksum)) {
+ return <NotFound />;
+ }
+
+ const token = urlObj.searchParams.get("token");
+
+ if (!token) return <NotFound />;
+
+ const hasToken = await prisma.verificationToken.findUnique({
+ where: {
+ token: hashToken(token),
+ },
+ });
+ if (!hasToken || hasToken.expires < new Date()) {
+ return <NotFound />;
+ }
+ const session = await getSession();
+ const user = session?.user as CustomUser;
+
+ if (!session) {
+ redirect(`/login?next=/account/general`);
+ }
+
+ await prisma.user.update({
+ where: {
+ id: user.id,
+ },
+ data: {
+ email: newEmail,
+ },
+ });
+
+ waitUntil(
+ sendEmail({
+ to: email as string,
+ subject: "Your email address has been changed",
+ react: EmailUpdated({
+ oldEmail: email,
+ newEmail: newEmail,
+ }),
+ test: process.env.NODE_ENV === "development",
+ }),
+ );
+
+ return <ConfirmEmailChangePageClient />;
+};
diff --git a/app/(auth)/auth/confirm-email-change/utils.ts b/app/(auth)/auth/confirm-email-change/utils.ts
new file mode 100644
index 00000000..f588cb33
--- /dev/null
+++ b/app/(auth)/auth/confirm-email-change/utils.ts
@@ -0,0 +1,6 @@
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth";
+
+export const getSession = async () => {
+ return getServerSession(authOptions);
+};
diff --git a/app/(auth)/layout.tsx b/app/(auth)/layout.tsx
index 35b318a7..6d123e17 100644
--- a/app/(auth)/layout.tsx
+++ b/app/(auth)/layout.tsx
@@ -1,14 +1,19 @@
+"use client";
+
+import { SessionProvider } from "next-auth/react";
import { Toaster } from "sonner";
import { ThemeProvider } from "@/components/theme-provider";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
- <ThemeProvider attribute="class" defaultTheme="light" enableSystem>
- <main>
- <Toaster closeButton richColors theme={"system"} />
- <div>{children}</div>
- </main>
- </ThemeProvider>
+ <SessionProvider>
+ <ThemeProvider attribute="class" defaultTheme="light" enableSystem>
+ <main>
+ <Toaster closeButton richColors theme="system" />
+ <div>{children}</div>
+ </main>
+ </ThemeProvider>
+ </SessionProvider>
);
}
diff --git a/components/account/account-header.tsx b/components/account/account-header.tsx
new file mode 100644
index 00000000..4318bf1f
--- /dev/null
+++ b/components/account/account-header.tsx
@@ -0,0 +1,31 @@
+import { NavMenu } from "../navigation-menu";
+
+export function AccountHeader() {
+ return (
+ <header>
+ <section className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">
+ <div className="space-y-1">
+ <h3 className="text-2xl font-semibold tracking-tight text-foreground">
+ User Account
+ </h3>
+ <p className="text-sm text-muted-foreground">Manage your profile</p>
+ </div>
+ </section>
+
+ <NavMenu
+ navigation={[
+ {
+ label: "General",
+ href: `/account/general`,
+ segment: `general`,
+ },
+ {
+ label: "Security",
+ href: `/account/security`,
+ segment: "security",
+ },
+ ]}
+ />
+ </header>
+ );
+}
diff --git a/components/account/update-mailSubscribe.tsx b/components/account/update-mailSubscribe.tsx
new file mode 100644
index 00000000..9fcbdfde
--- /dev/null
+++ b/components/account/update-mailSubscribe.tsx
@@ -0,0 +1,40 @@
+import { useOptimisticUpdate } from "../hooks/use-optimistic-update";
+import { Switch } from "../ui/switch";
+
+// TODO for latter use
+export const UpdateMailSubscribe = () => {
+ const { data, isLoading, update } = useOptimisticUpdate<{
+ subscribed: boolean;
+ }>("/api/user/subscribe", {
+ loading: "Updating email preferences...",
+ success: `Your ${process.env.NEXT_PUBLIC_BASE_URL} email preferences has been updated!`,
+ error: "Failed to update email preferences. Please try again.",
+ });
+
+ const subscribe = async (checked: boolean) => {
+ const method = checked ? "POST" : "DELETE";
+ const res = await fetch("/api/user/subscribe", {
+ method,
+ });
+ if (!res.ok) {
+ throw new Error("Failed to update email preferences");
+ }
+ return { subscribed: checked };
+ };
+
+ return (
+ <div className="flex items-center gap-x-2">
+ <Switch
+ checked={data?.subscribed}
+ onCheckedChange={(checked: boolean) => {
+ update(() => subscribe(checked), { subscribed: checked });
+ }}
+ />
+ <p className="text-sm text-muted-foreground transition-colors">
+ Subscribed to product updates
+ </p>
+ </div>
+ );
+};
+
+export default UpdateMailSubscribe;
diff --git a/components/account/upload-avatar.tsx b/components/account/upload-avatar.tsx
new file mode 100644
index 00000000..1455494e
--- /dev/null
+++ b/components/account/upload-avatar.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { ReactNode, useEffect, useState } from "react";
+
+import { useSession } from "next-auth/react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+
+import { convertDataUrlToFile, uploadImage } from "@/lib/utils";
+
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "../ui/card";
+import { FileUpload } from "../ui/file-upload";
+
+interface UploadAvatarProps {
+ title: string;
+ description: string;
+ helpText?: string | ReactNode;
+ buttonText?: string;
+}
+
+const UploadAvatar = ({
+ title,
+ description,
+ helpText,
+ buttonText,
+}: UploadAvatarProps) => {
+ const [uploading, setUploading] = useState(false);
+ const { data: session, update } = useSession();
+ const [image, setImage] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (session?.user?.image) {
+ setImage(session.user.image);
+ }
+ }, [session]);
+
+ return (
+ <form
+ onSubmit={async (e) => {
+ setUploading(true);
+ e.preventDefault();
+ if (!image) {
+ return;
+ }
+ const blob = convertDataUrlToFile({ dataUrl: image });
+ const blobUrl = await uploadImage(blob);
+ fetch("/api/account", {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ image: blobUrl }),
+ }).then(async (res) => {
+ setUploading(false);
+ if (res.status === 201) {
+ await update();
+ toast.success("Successfully updated your profile picture!");
+ } else {
+ const errorMessage = await res.text();
+ toast.error(errorMessage || "Something went wrong");
+ }
+ });
+ }}
+ className="rounded-lg"
+ >
+ <Card className="bg-transparent">
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ <CardDescription>{description}</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <FileUpload
+ accept="images"
+ className="h-24 w-24 rounded-full border border-gray-300"
+ iconClassName="w-5 h-5"
+ variant="plain"
+ imageSrc={image}
+ readFile
+ onChange={({ src, file }) => setImage(src)}
+ content={null}
+ maxFileSizeMB={2}
+ targetResolution={{ width: 160, height: 160, quality: 100 }}
+ />
+ </CardContent>
+ <CardFooter className="flex items-center justify-between rounded-b-lg border-t bg-muted px-6 py-3">
+ {typeof helpText === "string" ? (
+ <p
+ className="text-sm text-muted-foreground transition-colors"
+ dangerouslySetInnerHTML={{ __html: helpText || "" }}
+ />
+ ) : (
+ helpText
+ )}
+ <div className="shrink-0">
+ <Button
+ loading={uploading}
+ disabled={!image || session?.user?.image === image}
+ >
+ {buttonText || "Save Changes"}
+ </Button>
+ </div>
+ </CardFooter>
+ </Card>
+ </form>
+ );
+};
+
+export default UploadAvatar;
diff --git a/components/emails/email-updated.tsx b/components/emails/email-updated.tsx
new file mode 100644
index 00000000..55cf1b2b
--- /dev/null
+++ b/components/emails/email-updated.tsx
@@ -0,0 +1,70 @@
+import {
+ Body,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+
+export function EmailUpdated({
+ oldEmail = "[email protected]",
+ newEmail = "[email protected]",
+}: {
+ oldEmail: string;
+ newEmail: string;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Your email address has been updated</Preview>
+
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 w-[465px] p-5">
+ <Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">
+ <span className="font-bold tracking-tighter">Papermark</span>
+ </Text>
+ <Text className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ Your email address has been changed
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ The e-mail address for your Papermark account has been changed
+ from <strong>{oldEmail}</strong> to <strong>{newEmail}</strong>.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ If you did not make this change, please contact our support team
+ or{" "}
+ <Link href="https://app.papermark.io/account/general">
+ update your email address
+ </Link>
+ .
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ This message is being sent to your old e-mail address only.
+ </Text>
+ <Hr />
+ <Section className="mt-8 text-gray-400">
+ <Text className="text-xs">
+ © {new Date().getFullYear()}{" "}
+ <a
+ href="https://www.papermark.io"
+ className="text-gray-400 no-underline visited:text-gray-400 hover:text-gray-400"
+ target="_blank"
+ >
+ papermark.io
+ </a>
+ </Text>
+ </Section>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
+
+export default EmailUpdated;
diff --git a/components/emails/verification-mailChange.tsx b/components/emails/verification-mailChange.tsx
new file mode 100644
index 00000000..18d4eea4
--- /dev/null
+++ b/components/emails/verification-mailChange.tsx
@@ -0,0 +1,89 @@
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Hr,
+ Html,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+
+interface ConfirmEmailChangeProps {
+ email: string;
+ newEmail: string;
+ confirmUrl?: string;
+}
+
+export function ConfirmEmailChange({
+ email,
+ newEmail,
+ confirmUrl = "https://www.papermark.io",
+}: ConfirmEmailChangeProps) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Confirm your email address change</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 max-w-[500px] rounded border border-solid border-gray-200 px-10 py-5">
+ <Section>
+ <Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">
+ <span className="font-bold tracking-tighter">Papermark</span>
+ </Text>
+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ Your Papermark Email Change Confirmation Link
+ </Heading>
+ </Section>
+ <Heading className="text-sm leading-6 text-black">
+ Confirm your email address change
+ </Heading>
+ <Text className="text-sm leading-6 text-black">
+ Follow this link to confirm the update to your email from{" "}
+ <strong>{email}</strong> to <strong>{newEmail}</strong>.
+ </Text>
+ <Section className="my-8 text-center">
+ <Link
+ href={confirmUrl}
+ className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
+ style={{ padding: "12px 20px" }}
+ >
+ Confirm email change
+ </Link>
+ </Section>
+ <Text className="text-sm leading-6 text-black">
+ or copy and paste this URL into your browser:
+ </Text>
+ <Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">
+ {confirmUrl.replace(/^https?:\/\//, "")}
+ </Text>
+ <Hr />
+ <Section className="mt-8 text-gray-400">
+ <Text className="text-xs">
+ © {new Date().getFullYear()}{" "}
+ <a
+ href="https://www.papermark.io"
+ className="text-gray-400 no-underline visited:text-gray-400 hover:text-gray-400"
+ target="_blank"
+ >
+ papermark.io
+ </a>
+ </Text>
+ <Text className="text-xs">
+ This email was intended for{" "}
+ <span className="text-black">{email}</span>. If you were not
+ expecting this email, you can ignore this email. If you have any
+ feedback or questions about this email, simply reply to it.
+ </Text>
+ </Section>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
+
+export default ConfirmEmailChange;
diff --git a/components/hooks/use-optimistic-update.ts b/components/hooks/use-optimistic-update.ts
new file mode 100644
index 00000000..a8191f44
--- /dev/null
+++ b/components/hooks/use-optimistic-update.ts
@@ -0,0 +1,31 @@
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+export function useOptimisticUpdate<T>(
+ url: string,
+ toastCopy?: { loading: string; success: string; error: string },
+) {
+ const { data, isLoading, mutate } = useSWR<T>(url, fetcher);
+
+ return {
+ data,
+ isLoading,
+ update: async (fn: (data: T) => Promise<T>, optimisticData: T) => {
+ return toast.promise(
+ mutate(fn(data as T), {
+ optimisticData,
+ rollbackOnError: true,
+ populateCache: true,
+ revalidate: true,
+ }),
+ {
+ loading: toastCopy?.loading || "Updating...",
+ success: toastCopy?.success || "Successfully updated",
+ error: toastCopy?.error || "Failed to update",
+ },
+ );
+ },
+ };
+}
diff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsx
index b6bfe2d8..a2e4f890 100644
--- a/components/layouts/breadcrumb.tsx
+++ b/components/layouts/breadcrumb.tsx
@@ -196,6 +196,38 @@ const SettingsBreadcrumb = () => {
);
};
+const AccountBreadcrumb = () => {
+ const router = useRouter();
+ const path = router.pathname;
+
+ const accountTitle = useMemo(() => {
+ switch (path) {
+ case "/account/general":
+ return "General";
+ case "/account/security":
+ return "Security";
+ default:
+ return "Account";
+ }
+ }, [path]);
+
+ return (
+ <Breadcrumb>
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <BreadcrumbLink asChild>
+ <Link href="/account/general">Account</Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ <BreadcrumbSeparator />
+ <BreadcrumbItem>
+ <BreadcrumbPage>{accountTitle}</BreadcrumbPage>
+ </BreadcrumbItem>
+ </BreadcrumbList>
+ </Breadcrumb>
+ );
+};
+
const DocumentsBreadcrumb = () => {
const router = useRouter();
const { name } = router.query as { name: string[] };
@@ -368,6 +400,11 @@ export const AppBreadcrumb = () => {
return <SettingsBreadcrumb />;
}
+ // Account routes
+ if (path.startsWith("/account")) {
+ return <AccountBreadcrumb />;
+ }
+
// Root documents route
if (path === "/documents") {
return (
diff --git a/components/navigation-menu.tsx b/components/navigation-menu.tsx
index 6f815035..fb1faf2d 100644
--- a/components/navigation-menu.tsx
+++ b/components/navigation-menu.tsx
@@ -28,7 +28,7 @@ export const NavMenu: React.FC<React.PropsWithChildren<Props>> = ({
<nav
className={cn("sticky top-0 bg-background dark:bg-gray-900", className)}
>
- <div className="flex w-full items-center overflow-x-auto pl-1">
+ <div className="flex w-full items-center overflow-x-auto px-4">
<ul className="flex flex-row gap-4">
{navigation.map(({ label, href, segment, tag, disabled }) => (
<NavItem
diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsx
index fb2fa33d..08ed864a 100644
--- a/components/sidebar/app-sidebar.tsx
+++ b/components/sidebar/app-sidebar.tsx
@@ -10,12 +10,10 @@ import { TeamContextType, initialState, useTeam } from "@/context/team-context";
import Cookies from "js-cookie";
import {
BrushIcon,
- ChartNoAxesColumn,
- ChartNoAxesColumnIcon,
+ CircleUserRound,
CogIcon,
ContactIcon,
FolderIcon,
- HouseIcon,
Loader,
ServerIcon,
} from "lucide-react";
@@ -126,6 +124,29 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
},
],
},
+ {
+ title: "Account",
+ url: "/account/general",
+ icon: CircleUserRound,
+ isActive:
+ router.pathname.includes("account") &&
+ !router.pathname.includes("branding") &&
+ !router.pathname.includes("datarooms") &&
+ !router.pathname.includes("documents") &&
+ !router.pathname.includes("settings"),
+ items: [
+ {
+ title: "General",
+ url: "/account/general",
+ current: router.pathname.includes("account/general"),
+ },
+ {
+ title: "Security",
+ url: "/account/security",
+ current: router.pathname.includes("account/security"),
+ },
+ ],
+ },
],
};
diff --git a/components/sidebar/nav-user.tsx b/components/sidebar/nav-user.tsx
index d9e696f7..78089430 100644
--- a/components/sidebar/nav-user.tsx
+++ b/components/sidebar/nav-user.tsx
@@ -1,9 +1,12 @@
"use client";
+import Link from "next/link";
+
import { useState } from "react";
import {
ChevronsUpDown,
+ CircleUserRound,
FileTextIcon,
LifeBuoyIcon,
LogOut,
@@ -141,12 +144,14 @@ export function NavUser() {
</DropdownMenuLabel>
<DropdownMenuSeparator />
<ModeToggle />
- {/* <DropdownMenuGroup>
- <DropdownMenuItem>
- <Settings2 />
- User Settings
- </DropdownMenuItem>
- </DropdownMenuGroup> */}
+ <DropdownMenuGroup>
+ <Link href="/account/general">
+ <DropdownMenuItem>
+ <CircleUserRound />
+ Account
+ </DropdownMenuItem>
+ </Link>
+ </DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem
diff --git a/components/tab-menu.tsx b/components/tab-menu.tsx
index eb4fb25c..d9db6fad 100644
--- a/components/tab-menu.tsx
+++ b/components/tab-menu.tsx
@@ -28,7 +28,7 @@ export const TabMenu: React.FC<React.PropsWithChildren<Props>> = ({
<nav
className={cn("sticky top-0 bg-background dark:bg-gray-950", className)}
>
- <div className="flex w-full items-center overflow-x-auto pl-1">
+ <div className="flex w-full items-center overflow-x-auto px-4">
<ul className="flex flex-row gap-4">
{navigation.map(
({ label, href, value, currentValue, count, tag, disabled }) => (
diff --git a/components/ui/file-upload.tsx b/components/ui/file-upload.tsx
new file mode 100644
index 00000000..a5a320c9
--- /dev/null
+++ b/components/ui/file-upload.tsx
@@ -0,0 +1,289 @@
+import { DragEvent, ReactNode, useState } from "react";
+
+import { VariantProps, cva } from "class-variance-authority";
+import { CloudUpload, LoaderCircle } from "lucide-react";
+import { toast } from "sonner";
+
+import { cn } from "@/lib/utils";
+import { resizeImage } from "@/lib/utils/resize-image";
+
+type AcceptedFileFormats = "any" | "images" | "csv";
+
+const acceptFileTypes: Record<
+ AcceptedFileFormats,
+ { types: string[]; errorMessage?: string }
+> = {
+ any: { types: [] },
+ images: {
+ types: ["image/png", "image/jpg"],
+ errorMessage: "File type not supported (.png or .jpg only)",
+ },
+ csv: {
+ types: ["text/csv"],
+ errorMessage: "File type not supported (.csv only)",
+ },
+};
+
+const imageUploadVariants = cva(
+ "group relative isolate flex aspect-[1200/630] w-full flex-col items-center justify-center overflow-hidden bg-white transition-all hover:bg-gray-50",
+ {
+ variants: {
+ variant: {
+ default: "rounded-md border border-gray-300 shadow-sm",
+ plain: "",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+type FileUploadReadFileProps =
+ | {
+ /**
+ * Whether to automatically read the file and return the result as `src` to onChange
+ */
+ readFile?: false;
+ onChange?: (data: { file: File }) => void;
+ }
+ | {
+ /**
+ * Whether to automatically read the file and return the result as `src` to onChange
+ */
+ readFile: true;
+ onChange?: (data: { file: File; src: string }) => void;
+ };
+
+export type FileUploadProps = FileUploadReadFileProps & {
+ accept: AcceptedFileFormats;
+ className?: string;
+ iconClassName?: string;
+ previewClassName?: string;
+ /**
+ * Custom preview component to display instead of the default
+ */
+ customPreview?: ReactNode;
+ /**
+ * Image to display (generally for image uploads)
+ */
+ imageSrc?: string | null;
+
+ /**
+ * Whether to display a loading spinner
+ */
+ loading?: boolean;
+
+ /**
+ * Whether to allow clicking on the area to upload
+ */
+ clickToUpload?: boolean;
+
+ /**
+ * Whether to show instruction overlay when hovered
+ */
+ showHoverOverlay?: boolean;
+
+ /**
+ * Content to display below the upload icon (null to only display the icon)
+ */
+ content?: ReactNode | null;
+
+ /**
+ * Desired resolution to suggest and optionally resize to
+ */
+ targetResolution?: { width: number; height: number; quality: number };
+
+ /**
+ * A maximum file size (in megabytes) to check upon file selection
+ */
+ maxFileSizeMB?: number;
+
+ /**
+ * Accessibility label for screen readers
+ */
+ accessibilityLabel?: string;
+
+ disabled?: boolean;
+} & VariantProps<typeof imageUploadVariants>;
+
+export function FileUpload({
+ readFile,
+ onChange,
+ variant,
+ className,
+ iconClassName,
+ previewClassName,
+ customPreview,
+ accept = "any",
+ imageSrc,
+ loading = false,
+ clickToUpload = true,
+ showHoverOverlay = true,
+ content,
+ maxFileSizeMB = 0,
+ targetResolution,
+ accessibilityLabel = "File upload",
+ disabled = false,
+}: FileUploadProps) {
+ const [dragActive, setDragActive] = useState(false);
+ const [fileName, setFileName] = useState<string | null>(null);
+
+ const onFileChange = async (
+ e: React.ChangeEvent<HTMLInputElement> | DragEvent,
+ ) => {
+ const file =
+ "dataTransfer" in e
+ ? e.dataTransfer.files && e.dataTransfer.files[0]
+ : e.target.files && e.target.files[0];
+ if (!file) return;
+
+ setFileName(file.name);
+
+ if (maxFileSizeMB > 0 && file.size / 1024 / 1024 > maxFileSizeMB) {
+ toast.error(`File size too big (max ${maxFileSizeMB} MB)`);
+ return;
+ }
+
+ const acceptedTypes = acceptFileTypes[accept].types;
+
+ if (acceptedTypes.length && !acceptedTypes.includes(file.type)) {
+ toast.error(
+ acceptFileTypes[accept].errorMessage ?? "File type not supported",
+ );
+ return;
+ }
+
+ let fileToUse = file;
+
+ // Add image resizing logic
+ if (targetResolution && file.type.startsWith("image/")) {
+ try {
+ const resizedFile = await resizeImage(file, targetResolution);
+ const blob = await fetch(resizedFile).then((r) => r.blob());
+ fileToUse = new File([blob], file.name, { type: file.type });
+ } catch (error) {
+ console.error("Error resizing image:", error);
+ // Fallback to original file if resize fails
+ }
+ }
+
+ // File reading logic
+ if (readFile) {
+ const reader = new FileReader();
+ reader.onload = (e) =>
+ onChange?.({ src: e.target?.result as string, file: fileToUse });
+ reader.readAsDataURL(fileToUse);
+ return;
+ }
+
+ onChange?.({ file: fileToUse });
+ };
+
+ return (
+ <label
+ className={cn(
+ imageUploadVariants({ variant }),
+ !disabled
+ ? cn(clickToUpload && "cursor-pointer")
+ : "cursor-not-allowed",
+ className,
+ )}
+ >
+ {loading && (
+ <div className="absolute inset-0 z-[5] flex items-center justify-center rounded-[inherit] bg-white">
+ <LoaderCircle />
+ </div>
+ )}
+ <div
+ className="absolute inset-0 z-[5]"
+ onDragOver={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragActive(true);
+ }}
+ onDragEnter={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragActive(true);
+ }}
+ onDragLeave={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragActive(false);
+ }}
+ onDrop={async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onFileChange(e);
+ setDragActive(false);
+ }}
+ />
+ <div
+ className={cn(
+ "absolute inset-0 z-[3] flex flex-col items-center justify-center rounded-[inherit] border-2 border-transparent bg-white transition-all",
+ disabled && "bg-gray-50",
+ dragActive &&
+ !disabled &&
+ "cursor-copy border-black bg-gray-50 opacity-100",
+ imageSrc
+ ? cn(
+ "opacity-0",
+ showHoverOverlay && !disabled && "group-hover:opacity-100",
+ )
+ : cn(!disabled && "group-hover:bg-gray-50"),
+ )}
+ >
+ <CloudUpload
+ className={cn(
+ "size-7 transition-all duration-75",
+ !disabled
+ ? cn(
+ "text-gray-500 group-hover:scale-110 group-active:scale-95",
+ dragActive ? "scale-110" : "scale-100",
+ )
+ : "text-gray-400",
+ iconClassName,
+ )}
+ />
+ {content !== null && (
+ <div
+ className={cn(
+ "mt-2 text-center text-sm text-gray-500",
+ disabled && "text-gray-400",
+ )}
+ >
+ {content ?? (
+ <>
+ <p>Drag and drop {clickToUpload && "or click"} to upload.</p>
+ </>
+ )}
+ </div>
+ )}
+ <span className="sr-only">{accessibilityLabel}</span>
+ </div>
+ {imageSrc &&
+ (customPreview ?? (
+ <img
+ src={imageSrc}
+ alt="Preview"
+ className={cn(
+ "h-full w-full rounded-[inherit] object-cover",
+ previewClassName,
+ )}
+ />
+ ))}
+ {clickToUpload && (
+ <div className="sr-only mt-1 flex shadow-sm">
+ <input
+ key={fileName} // Gets us a fresh input every time a file is uploaded
+ type="file"
+ accept={acceptFileTypes[accept].types.join(",")}
+ onChange={onFileChange}
+ disabled={disabled}
+ />
+ </div>
+ )}
+ </label>
+ );
+}
diff --git a/components/ui/form.tsx b/components/ui/form.tsx
index 546c1ef6..469fd196 100644
--- a/components/ui/form.tsx
+++ b/components/ui/form.tsx
@@ -1,6 +1,15 @@
-import { InputHTMLAttributes, ReactNode, useMemo, useState } from "react";
+import {
+ InputHTMLAttributes,
+ ReactNode,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+
+import { toast } from "sonner";
import { cn } from "@/lib/utils";
+import { validateEmail } from "@/lib/utils/validate-email";
import { Button } from "./button";
import {
@@ -21,6 +30,7 @@ export function Form({
buttonText = "Save Changes",
disabledTooltip,
handleSubmit,
+ validate,
}: {
title: string;
description: string;
@@ -29,9 +39,15 @@ export function Form({
buttonText?: string;
disabledTooltip?: string | ReactNode;
handleSubmit: (data: any) => Promise<any>;
+ validate?: (data: string) => boolean;
}) {
- const [value, setValue] = useState(inputAttrs.defaultValue);
const [saving, setSaving] = useState(false);
+ const [value, setValue] = useState(inputAttrs.defaultValue);
+
+ useEffect(() => {
+ if (inputAttrs.defaultValue) setValue(inputAttrs.defaultValue);
+ }, [inputAttrs.defaultValue]);
+
const saveDisabled = useMemo(() => {
return saving || !value || value === inputAttrs.defaultValue;
}, [saving, value, inputAttrs.defaultValue]);
@@ -41,9 +57,13 @@ export function Form({
onSubmit={async (e) => {
e.preventDefault();
setSaving(true);
- await handleSubmit({
- [inputAttrs.name as string]: value,
- });
+ if (!validate || validate(value?.toString() || "")) {
+ await handleSubmit({
+ [inputAttrs.name as string]: value?.toString(),
+ });
+ } else {
+ toast.error("Please enter a valid value");
+ }
setSaving(false);
}}
className="rounded-lg"
@@ -57,10 +77,12 @@ export function Form({
{typeof inputAttrs.defaultValue === "string" ? (
<Input
{...inputAttrs}
+ value={value}
type={inputAttrs.type || "text"}
required
- disabled={disabledTooltip ? true : false}
+ disabled={!!disabledTooltip}
onChange={(e) => setValue(e.target.value)}
+ onBlur={(e) => setValue(e.target.value.trim())}
className={cn(
"w-full max-w-md focus:border-gray-500 focus:outline-none focus:ring-gray-500",
{
@@ -75,10 +97,14 @@ export function Form({
)}
</CardContent>
<CardFooter className="flex items-center justify-between rounded-b-lg border-t bg-muted px-6 py-3">
- <p className="text-sm text-muted-foreground transition-colors">
- {helpText || ""}
- </p>
-
+ {typeof helpText === "string" ? (
+ <p
+ className="text-sm text-muted-foreground transition-colors"
+ dangerouslySetInnerHTML={{ __html: helpText || "" }}
+ />
+ ) : (
+ helpText
+ )}
<div className="shrink-0">
<Button loading={saving} disabled={saveDisabled}>
{buttonText}
diff --git a/lib/emails/send-mail-verification.ts b/lib/emails/send-mail-verification.ts
new file mode 100644
index 00000000..cd83f042
--- /dev/null
+++ b/lib/emails/send-mail-verification.ts
@@ -0,0 +1,38 @@
+import ConfirmEmailChange from "@/components/emails/verification-mailChange";
+
+import { sendEmail } from "@/lib/resend";
+
+import { generateChecksum } from "../utils/generate-checksum";
+
+export const sendEmailChangeVerificationRequestEmail = async (params: {
+ email: string;
+ url: string;
+ newEmail: string;
+}) => {
+ const { url, email, newEmail } = params;
+ const checksum = generateChecksum(url);
+
+ const verificationUrlParams = new URLSearchParams({
+ verification_url: url,
+ email,
+ newEmail,
+ checksum,
+ }).toString();
+ const confirmUrl = `${process.env.NEXTAUTH_URL}/auth/confirm-email-change?${verificationUrlParams}`;
+ const emailTemplate = ConfirmEmailChange({
+ confirmUrl,
+ email,
+ newEmail,
+ });
+
+ try {
+ await sendEmail({
+ to: email as string,
+ subject: "Confirm your email address change for Papermark!",
+ react: emailTemplate,
+ test: process.env.NODE_ENV === "development",
+ });
+ } catch (e) {
+ console.error(e);
+ }
+};
diff --git a/lib/utils.ts b/lib/utils.ts
index 60ea428b..adbb77b5 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -446,10 +446,13 @@ export const validateImageDimensions = (
});
};
-export const uploadImage = async (file: File) => {
+export const uploadImage = async (
+ file: File,
+ uploadType: "profile" | "assets" = "assets",
+) => {
const newBlob = await upload(file.name, file, {
access: "public",
- handleUploadUrl: "/api/file/logo-upload",
+ handleUploadUrl: `/api/file/image-upload?type=${uploadType}`,
});
return newBlob.url;
@@ -535,3 +538,5 @@ export function hexToRgb(hex: string) {
let b = (bigint & 255) / 255; // Convert to 0-1 range
return rgb(r, g, g);
}
+
+export const trim = (u: unknown) => (typeof u === "string" ? u.trim() : u);
diff --git a/pages/account/general.tsx b/pages/account/general.tsx
new file mode 100644
index 00000000..b1aa5d0a
--- /dev/null
+++ b/pages/account/general.tsx
@@ -0,0 +1,95 @@
+import { NextPage } from "next";
+
+import { useSession } from "next-auth/react";
+import { toast } from "sonner";
+
+import { AccountHeader } from "@/components/account/account-header";
+import UploadAvatar from "@/components/account/upload-avatar";
+import AppLayout from "@/components/layouts/app";
+import { Form } from "@/components/ui/form";
+
+import { validateEmail } from "@/lib/utils/validate-email";
+
+const ProfilePage: NextPage = () => {
+ const { data: session, update } = useSession();
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <AccountHeader />
+ <div className="space-y-6">
+ <Form
+ title="Your Name"
+ description="This will be your display name on Papermark.io."
+ inputAttrs={{
+ name: "name",
+ defaultValue: session?.user?.name ?? "",
+ placeholder: "Dino Hems",
+ maxLength: 32,
+ }}
+ helpText="Max 32 characters."
+ handleSubmit={(data) =>
+ fetch("/api/account", {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ }).then(async (res) => {
+ if (res.status === 201) {
+ update();
+ toast.success("Successfully updated your name!");
+ } else {
+ const { error } = await res.json();
+ toast.error(error?.message);
+ }
+ })
+ }
+ />
+ <Form
+ title="Your Email"
+ description="This will be the email you use to log in to Papermark.io and receive notification. A confirmation is required for changes."
+ inputAttrs={{
+ name: "email",
+ defaultValue: session?.user?.email ?? undefined,
+ placeholder: "[email protected]",
+ maxLength: 52,
+ type: "email",
+ }}
+ // TODO: MAIL SUBSCRIPTION
+ // helpText={<UpdateMailSubscribe />}
+ validate={validateEmail}
+ helpText=""
+ handleSubmit={(data) =>
+ fetch("/api/account", {
+ method: "PATCH",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ }).then(async (res) => {
+ if (res.status === 201) {
+ update();
+ toast.success(
+ `A confirmation email has been sent to ${data.email}.`,
+ );
+ } else {
+ const { error } = await res.json();
+ toast.error(error.message);
+ }
+ })
+ }
+ />
+ <UploadAvatar
+ title="Your Avatar"
+ description={`This is your avatar image on ${process.env.NEXT_PUBLIC_BASE_URL}.`}
+ helpText="Square image recommended. Accepted file types: .png, .jpg. Max file
+ size: 2MB."
+ />
+ </div>
+ </main>
+ </AppLayout>
+ );
+};
+
+export default ProfilePage;
diff --git a/pages/account/security.tsx b/pages/account/security.tsx
new file mode 100644
index 00000000..5536bd92
--- /dev/null
+++ b/pages/account/security.tsx
@@ -0,0 +1,71 @@
+import { NextPage } from "next";
+
+import {
+ type CredentialCreationOptionsJSON,
+ create,
+} from "@github/webauthn-json";
+import { toast } from "sonner";
+
+import { AccountHeader } from "@/components/account/account-header";
+import AppLayout from "@/components/layouts/app";
+import Passkey from "@/components/shared/icons/passkey";
+import { Button } from "@/components/ui/button";
+
+const ProfilePage: NextPage = () => {
+ async function registerPasskey() {
+ const createOptionsResponse = await fetch("/api/passkeys/register", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ start: true, finish: false, credential: null }),
+ });
+
+ const { createOptions } = await createOptionsResponse.json();
+
+ // Open "register passkey" dialog
+ const credential = await create(
+ createOptions as CredentialCreationOptionsJSON,
+ );
+
+ const response = await fetch("/api/passkeys/register", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ start: false, finish: true, credential }),
+ });
+
+ if (response.ok) {
+ toast.success("Registered passkey successfully!");
+ return;
+ }
+ // Now the user has registered their passkey and can use it to log in.
+ }
+
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <AccountHeader />
+ <div className="space-y-6">
+ <div className="rounded-lg border border-muted p-10">
+ <div className="space-y-6">
+ <div className="space-y-3">
+ <h2 className="text-xl font-medium">Register a passkey</h2>
+ <p className="mt-3 text-sm text-muted-foreground">
+ Never use a password or oauth again. Register a passkey to
+ make logging in easy.
+ </p>
+ </div>
+ <Button
+ onClick={() => registerPasskey()}
+ className="flex items-center justify-center space-x-2"
+ >
+ <Passkey className="h-4 w-4" />
+ <span>Register a new passkey</span>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </main>
+ </AppLayout>
+ );
+};
+
+export default ProfilePage;
diff --git a/pages/api/account/index.tsx b/pages/api/account/index.tsx
new file mode 100644
index 00000000..b56a8e75
--- /dev/null
+++ b/pages/api/account/index.tsx
@@ -0,0 +1,96 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { waitUntil } from "@vercel/functions";
+import { getServerSession } from "next-auth";
+import { z } from "zod";
+
+import { hashToken } from "@/lib/api/auth/token";
+import { sendEmailChangeVerificationRequestEmail } from "@/lib/emails/send-mail-verification";
+import { errorhandler } from "@/lib/errorHandler";
+import { newId } from "@/lib/id-helper";
+import prisma from "@/lib/prisma";
+import { ratelimit } from "@/lib/redis";
+import { CustomUser } from "@/lib/types";
+import { trim } from "@/lib/utils";
+
+import { authOptions } from "../auth/[...nextauth]";
+
+const updateUserSchema = z.object({
+ name: z.preprocess(trim, z.string().min(1).max(64)).optional(),
+ email: z.preprocess(trim, z.string().email()).optional(),
+ image: z.string().url().optional(),
+});
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "PATCH") {
+ // POST /api/account
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ throw new Error("Unauthorized");
+ }
+ const user = session.user as CustomUser;
+ const { email, image, name } = await updateUserSchema.parseAsync(
+ await req.body,
+ );
+
+ try {
+ if (email && email !== session.user?.email) {
+ const userWithEmail = await prisma.user.findUnique({
+ where: {
+ email,
+ },
+ });
+ if (userWithEmail) {
+ throw new Error("Email is already in use.");
+ }
+ const { success } = await ratelimit(6, "6 h").limit(
+ `email-change-request:${user.id}`,
+ );
+ if (!success) {
+ throw new Error(
+ "You've requested too many email change requests. Please try again later.",
+ );
+ }
+ const token = newId("email");
+ const expiresIn = 15 * 60 * 1000;
+ await prisma.verificationToken.create({
+ data: {
+ identifier: user.id,
+ token: hashToken(token),
+ expires: new Date(Date.now() + expiresIn),
+ },
+ });
+ waitUntil(
+ sendEmailChangeVerificationRequestEmail({
+ email: user.email as string,
+ newEmail: email,
+ url: `${process.env.NEXTAUTH_URL}/auth/confirm-email-change?token=${token}`,
+ }),
+ );
+
+ return res.status(201).json({ message: "success" });
+ }
+
+ const response = await prisma.user.update({
+ where: {
+ id: user.id,
+ },
+ data: {
+ ...(name && { name }),
+ ...(image && { image }),
+ },
+ });
+
+ return res.status(201).json(response);
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else {
+ res.setHeader("Allow", ["PATCH"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].ts
index 93738099..03485cb2 100644
--- a/pages/api/auth/[...nextauth].ts
+++ b/pages/api/auth/[...nextauth].ts
@@ -94,13 +94,26 @@ export const authOptions: NextAuthOptions = {
},
},
callbacks: {
- jwt: async ({ token, user }) => {
+ jwt: async (params) => {
+ const { token, user, trigger } = params;
if (!token.email) {
return {};
}
if (user) {
token.user = user;
}
+ // refresh the user data
+ if (trigger === "update") {
+ const user = token?.user as CustomUser;
+ const refreshedUser = await prisma.user.findUnique({
+ where: { id: user.id },
+ });
+ if (refreshedUser) {
+ token.user = refreshedUser;
+ } else {
+ return {};
+ }
+ }
return token;
},
session: async ({ session, token }) => {
diff --git a/pages/api/file/logo-upload.ts b/pages/api/file/image-upload.ts
similarity index 68%
rename from pages/api/file/logo-upload.ts
rename to pages/api/file/image-upload.ts
index c2a532cb..47bb5609 100644
--- a/pages/api/file/logo-upload.ts
+++ b/pages/api/file/image-upload.ts
@@ -7,11 +7,37 @@ import { CustomUser } from "@/lib/types";
import { authOptions } from "../auth/[...nextauth]";
+const uploadConfig = {
+ profile: {
+ allowedContentTypes: ["image/png", "image/jpg"],
+ maximumSizeInBytes: 2 * 1024 * 1024, // 2MB
+ },
+ assets: {
+ allowedContentTypes: [
+ "image/png",
+ "image/jpeg",
+ "image/jpg",
+ "image/svg+xml",
+ "image/x-icon",
+ "image/ico",
+ ],
+ maximumSizeInBytes: 5 * 1024 * 1024, // 5MB
+ },
+};
+
+// logo-upload/?type= "profile" | "assets"
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const body = req.body as HandleUploadBody;
+ const type = Array.isArray(req.query.type)
+ ? req.query.type[0]
+ : req.query.type;
+
+ if (!type || !(type in uploadConfig)) {
+ return res.status(400).json({ error: "Invalid upload type specified." });
+ }
try {
const jsonResponse = await handleUpload({
@@ -27,15 +53,10 @@ export default async function handler(
}
return {
- allowedContentTypes: [
- "image/png",
- "image/jpeg",
- "image/jpg",
- "image/svg+xml",
- "image/x-icon",
- "image/ico",
- ],
- maximumSizeInBytes: 5 * 1024 * 1024, // 5 MB
+ allowedContentTypes:
+ uploadConfig[type as keyof typeof uploadConfig].allowedContentTypes,
+ maximumSizeInBytes:
+ uploadConfig[type as keyof typeof uploadConfig].maximumSizeInBytes,
metadata: JSON.stringify({
// optional, sent to your server on upload completion
userId: (session.user as CustomUser).id,
diff --git a/pages/datarooms/[id]/groups/[groupId]/index.tsx b/pages/datarooms/[id]/groups/[groupId]/index.tsx
index 3815fc71..b5f0307b 100644
--- a/pages/datarooms/[id]/groups/[groupId]/index.tsx
+++ b/pages/datarooms/[id]/groups/[groupId]/index.tsx
@@ -61,7 +61,7 @@ export default function DataroomGroupPage() {
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ name: updateData?.name.trim() }),
+ body: JSON.stringify(updateData),
},
).then(async (res) => {
if (res.status === 200) {
diff --git a/pages/datarooms/[id]/permissions/[groupId]/index.tsx b/pages/datarooms/[id]/permissions/[groupId]/index.tsx
index 3815fc71..b5f0307b 100644
--- a/pages/datarooms/[id]/permissions/[groupId]/index.tsx
+++ b/pages/datarooms/[id]/permissions/[groupId]/index.tsx
@@ -61,7 +61,7 @@ export default function DataroomGroupPage() {
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ name: updateData?.name.trim() }),
+ body: JSON.stringify(updateData),
},
).then(async (res) => {
if (res.status === 200) {
diff --git a/pages/datarooms/[id]/settings/index.tsx b/pages/datarooms/[id]/settings/index.tsx
index 00942752..33be77aa 100644
--- a/pages/datarooms/[id]/settings/index.tsx
+++ b/pages/datarooms/[id]/settings/index.tsx
@@ -69,7 +69,7 @@ export default function Settings() {
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ name: updateData.name.trim() }),
+ body: JSON.stringify(updateData),
}).then(async (res) => {
if (res.status === 200) {
await Promise.all([
diff --git a/pages/settings/general.tsx b/pages/settings/general.tsx
index c7877175..62d531bd 100644
--- a/pages/settings/general.tsx
+++ b/pages/settings/general.tsx
@@ -1,48 +1,15 @@
import { useTeam } from "@/context/team-context";
-import {
- type CredentialCreationOptionsJSON,
- create,
-} from "@github/webauthn-json";
import { toast } from "sonner";
import { mutate } from "swr";
import AppLayout from "@/components/layouts/app";
import DeleteTeam from "@/components/settings/delete-team";
import { SettingsHeader } from "@/components/settings/settings-header";
-import Passkey from "@/components/shared/icons/passkey";
-import { Button } from "@/components/ui/button";
import { Form } from "@/components/ui/form";
export default function General() {
const teamInfo = useTeam();
- async function registerPasskey() {
- const createOptionsResponse = await fetch("/api/passkeys/register", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ start: true, finish: false, credential: null }),
- });
-
- const { createOptions } = await createOptionsResponse.json();
-
- // Open "register passkey" dialog
- const credential = await create(
- createOptions as CredentialCreationOptionsJSON,
- );
-
- const response = await fetch("/api/passkeys/register", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ start: false, finish: true, credential }),
- });
-
- if (response.ok) {
- toast.success("Registered passkey successfully!");
- return;
- }
- // Now the user has registered their passkey and can use it to log in.
- }
-
return (
<AppLayout>
<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
@@ -73,7 +40,7 @@ export default function General() {
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ name: updateData?.name.trim() }),
+ body: JSON.stringify(updateData),
}).then(async (res) => {
if (res.status === 200) {
await Promise.all([
@@ -88,26 +55,6 @@ export default function General() {
})
}
/>
-
- <div className="rounded-lg border border-muted p-10">
- <div className="space-y-6">
- <div className="space-y-3">
- <h2 className="text-xl font-medium">Register a passkey</h2>
- <p className="mt-3 text-sm text-secondary-foreground">
- Never use a password or oauth again. Register a passkey to
- make logging in easy.
- </p>
- </div>
- <Button
- onClick={() => registerPasskey()}
- className="flex items-center justify-center space-x-2"
- >
- <Passkey className="h-4 w-4" />
- <span>Register a new passkey</span>
- </Button>
- </div>
- </div>
-
<DeleteTeam />
</div>
</main>