Skip to content

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

improve invitation accept

Ashish Viradiya755d8168be83
diff --git a/app/(auth)/login/page.tsx b/app/(auth)/login/page.tsx
index da35c01d..f138c83c 100644
--- a/app/(auth)/login/page.tsx
+++ b/app/(auth)/login/page.tsx
@@ -206,7 +206,7 @@ export default function Login() {
<a
href="https://www.papermark.com/terms"
target="_blank"
- className="underline"
+ className="underline hover:text-gray-900"
>
Terms of Service
</a>{" "}
@@ -214,7 +214,7 @@ export default function Login() {
<a
href="https://www.papermark.com/privacy"
target="_blank"
- className="underline"
+ className="underline hover:text-gray-900"
>
Privacy Policy
</a>
diff --git a/app/(auth)/verify/invitation/page.tsx b/app/(auth)/verify/invitation/page.tsx
new file mode 100644
index 00000000..6741a392
--- /dev/null
+++ b/app/(auth)/verify/invitation/page.tsx
@@ -0,0 +1,160 @@
+import Link from "next/link";
+
+import NotFound from "@/pages/404";
+import { format } from "date-fns";
+import { ClockIcon, MailIcon } from "lucide-react";
+
+import { generateChecksum } from "@/lib/utils/generate-checksum";
+
+import { Button } from "@/components/ui/button";
+
+export default function VerifyInvitationPage({
+ searchParams,
+}: {
+ searchParams: {
+ verification_url?: string;
+ checksum?: string;
+ type?: string;
+ teamId?: string;
+ token?: string;
+ email?: string;
+ expiresAt?: string;
+ };
+}) {
+ const { verification_url, checksum, type, teamId, token, email, expiresAt } =
+ searchParams;
+
+ if (type !== "invitation") {
+ return <NotFound />;
+ }
+
+ // Validate required parameters
+ if (!verification_url || !checksum || !teamId || !token || !email) {
+ return <NotFound />;
+ }
+
+ // Server-side validation
+ const isValidVerificationUrl = (url: string, checksum: string): boolean => {
+ try {
+ const urlObj = new URL(url);
+ 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 />;
+ }
+
+ return (
+ <div className="flex h-screen w-full flex-wrap">
+ {/* Left part */}
+ <div className="flex w-full justify-center bg-white md:w-1/2 lg:w-2/5">
+ <div
+ className="absolute inset-x-0 top-10 -z-10 flex transform-gpu justify-center overflow-hidden blur-3xl"
+ aria-hidden="true"
+ ></div>
+ <div className="z-10 mx-5 mt-[calc(20vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0">
+ <div className="flex flex-col items-center justify-center space-y-3 px-4 py-6 pt-8 text-center sm:px-16">
+ <Link href="/">
+ <span className="text-balance text-2xl font-semibold text-gray-800">
+ Welcome to Papermark
+ </span>
+ </Link>
+ <h3 className="text-balance py-1 text-sm font-normal text-gray-800">
+ You've been invited to join a team on Papermark
+ </h3>
+ <div className="mt-2 flex items-center gap-2 rounded-full bg-gray-50 px-4 py-2 text-sm text-gray-600 shadow-sm">
+ <MailIcon className="h-4 w-4 text-gray-400" />
+ {email}
+ </div>
+ </div>
+ <div className="flex flex-col gap-4 px-4 pt-8 sm:px-16">
+ <div className="relative">
+ <Link href={verification_url}>
+ <Button className="focus:shadow-outline w-full transform rounded-lg bg-gray-800 px-4 py-3 text-white transition-colors duration-300 ease-in-out hover:bg-gray-900 focus:outline-none">
+ Accept Invitation
+ </Button>
+ </Link>
+ </div>
+ <div className="text-center text-sm text-gray-500">
+ <p className="flex items-center justify-center gap-1.5 rounded-md bg-amber-50 px-3 py-2 text-amber-700">
+ <ClockIcon className="h-4 w-4 text-amber-500" />
+ <span>
+ Expires on{" "}
+ <span className="font-medium">
+ {format(new Date(expiresAt!), "MMM d, yyyy")}
+ </span>{" "}
+ at{" "}
+ <span className="font-medium">
+ {format(new Date(expiresAt!), "h:mm a")}
+ </span>
+ </span>
+ </p>
+ </div>
+ </div>
+ <p className="mt-10 w-full max-w-md px-4 text-xs text-muted-foreground sm:px-16">
+ By accepting this invitation, you acknowledge that you have read and
+ agree to Papermark&apos;s{" "}
+ <a
+ href="https://www.papermark.com/terms"
+ target="_blank"
+ className="underline hover:text-gray-900"
+ >
+ Terms of Service
+ </a>{" "}
+ and{" "}
+ <a
+ href="https://www.papermark.com/privacy"
+ target="_blank"
+ className="underline hover:text-gray-900"
+ >
+ Privacy Policy
+ </a>
+ .
+ </p>
+ </div>
+ </div>
+ <div className="hidden w-full justify-center bg-gray-800 md:flex md:w-1/2 lg:w-3/5">
+ <div className="flex w-full max-w-5xl px-4 py-20 md:px-8">
+ <div
+ className="mx-auto flex w-full max-w-5xl justify-center rounded-3xl bg-gray-800 px-4 py-20 md:px-8"
+ id="features"
+ >
+ <div className="flex flex-col items-center">
+ {/* Image container */}
+ <div className="mb-4 h-64 w-64">
+ <img
+ className="h-full w-full rounded-2xl object-cover shadow-2xl"
+ src="/_static/testimonials/jaski.jpeg"
+ alt="Jaski"
+ />
+ </div>
+ {/* Text content */}
+ <div className="max-w-xl text-center">
+ <blockquote className="text-l text-balance leading-8 text-gray-100 sm:text-xl sm:leading-9">
+ <p>
+ True builders listen to their users and build what they
+ need. Thanks Papermark team for solving a big pain point.
+ DocSend monopoly will end soon!
+ </p>
+ </blockquote>
+ <figcaption className="mt-4">
+ <div className="text-balance font-semibold text-white">
+ Jaski
+ </div>
+ <div className="text-balance text-gray-400">
+ Founder, Townhall Network
+ </div>
+ </figcaption>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/app/(auth)/verify/page.tsx b/app/(auth)/verify/page.tsx
index 93ad08f8..d7ef8039 100644
--- a/app/(auth)/verify/page.tsx
+++ b/app/(auth)/verify/page.tsx
@@ -67,7 +67,7 @@ export default function VerifyPage({
<a
href="https://www.papermark.com/terms"
target="_blank"
- className="underline"
+ className="underline hover:text-gray-900"
>
Terms of Service
</a>{" "}
@@ -75,7 +75,7 @@ export default function VerifyPage({
<a
href="https://www.papermark.com/privacy"
target="_blank"
- className="underline"
+ className="underline hover:text-gray-900"
>
Privacy Policy
</a>
@@ -122,4 +122,4 @@ export default function VerifyPage({
</div>
</div>
);
-}
+};
\ No newline at end of file
diff --git a/components/view/visitor-graph.tsx b/components/view/visitor-graph.tsx
index 1df9cfea..7e72aabc 100644
--- a/components/view/visitor-graph.tsx
+++ b/components/view/visitor-graph.tsx
@@ -192,11 +192,11 @@ export default function ViewDurationSummary({
<p className="mt-4 w-full max-w-md px-4 text-xs text-muted-foreground sm:px-16">
By clicking continue, you acknowledge that you have read and agree
to Papermark&apos;s{" "}
- <Link href="/terms" target="_blank" className="underline">
+ <Link href="/terms" target="_blank" className="underline hover:text-gray-900">
Terms of Service
</Link>{" "}
and{" "}
- <Link href="/privacy" target="_blank" className="underline">
+ <Link href="/privacy" target="_blank" className="underline hover:text-gray-900">
Privacy Policy
</Link>
.
diff --git a/lib/middleware/app.ts b/lib/middleware/app.ts
index 75f5c8b2..361a759e 100644
--- a/lib/middleware/app.ts
+++ b/lib/middleware/app.ts
@@ -5,6 +5,7 @@ import { getToken } from "next-auth/jwt";
export default async function AppMiddleware(req: NextRequest) {
const url = req.nextUrl;
const path = url.pathname;
+ const isInvited = url.searchParams.has("invitation");
const token = (await getToken({
req,
secret: process.env.NEXTAUTH_SECRET,
@@ -33,7 +34,8 @@ export default async function AppMiddleware(req: NextRequest) {
token?.email &&
token?.user?.createdAt &&
new Date(token?.user?.createdAt).getTime() > Date.now() - 10000 &&
- path !== "/welcome"
+ path !== "/welcome" &&
+ !isInvited
) {
return NextResponse.redirect(new URL("/welcome", req.url));
}
diff --git a/lib/utils.ts b/lib/utils.ts
index 422c53f6..712d502b 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -6,8 +6,10 @@ import { type ClassValue, clsx } from "clsx";
import crypto from "crypto";
import ms from "ms";
import { customAlphabet } from "nanoid";
+import { NextRouter } from "next/router";
import { ThreadMessage } from "openai/resources/beta/threads/messages/messages";
import { rgb } from "pdf-lib";
+import { ParsedUrlQuery } from "querystring";
import { toast } from "sonner";
import { twMerge } from "tailwind-merge";
@@ -559,4 +561,26 @@ export const getBreadcrumbPath = (path: string[]) => {
};
})
];
+};
+
+export const handleInvitationStatus = (
+ invitationStatus: 'accepted' | 'teamMember',
+ queryParams: ParsedUrlQuery,
+ router: NextRouter,
+) => {
+ switch (invitationStatus) {
+ case 'accepted':
+ toast.success("Welcome to the team! You've successfully joined.");
+ break;
+ case 'teamMember':
+ toast.error("You've already accepted this invitation!");
+ break;
+ default:
+ toast.error("Invalid invitation status");
+ }
+
+ delete queryParams["invitation"];
+ router.replace("/documents", undefined, {
+ shallow: true,
+ });
};
\ No newline at end of file
diff --git a/pages/api/teams/[teamId]/invitations/accept.ts b/pages/api/teams/[teamId]/invitations/accept.ts
index cc4c6e01..335b13c3 100644
--- a/pages/api/teams/[teamId]/invitations/accept.ts
+++ b/pages/api/teams/[teamId]/invitations/accept.ts
@@ -13,19 +13,37 @@ export default async function handle(
res: NextApiResponse,
) {
if (req.method === "GET") {
- // GET /api/teams/:teamId/invitations/accept
+ // GET /api/teams/:teamId/invitations/accept?token=...&email=...
const session = await getServerSession(req, res, authOptions);
- const { teamId } = req.query as { teamId: string };
+ const { teamId, token, email } = req.query as { teamId: string; token?: string; email?: string };
+ // Log the request for debugging
+ console.log("Invitation acceptance request:", { teamId, token, email });
+
+ // Check if user is authenticated
if (!session) {
- res.redirect(`/login?next=/api/teams/${teamId}/invitations/accept`);
+ // Store the invitation details in the redirect URL
+ const redirectUrl = `/login?next=/api/teams/${teamId}/invitations/accept`;
+ const params = new URLSearchParams();
+
+ if (token) params.append("token", token);
+ if (email) params.append("email", email);
+
+ const finalRedirectUrl = params.toString()
+ ? `${redirectUrl}&${params.toString()}`
+ : redirectUrl;
+
+ console.log("Redirecting to login:", finalRedirectUrl);
+ res.redirect(finalRedirectUrl);
return;
}
const userId = (session.user as CustomUser).id;
+ const userEmail = (session.user as CustomUser).email;
try {
+ // Check if user is already in the team
const userTeam = await prisma.userTeam.findFirst({
where: {
teamId,
@@ -34,18 +52,42 @@ export default async function handle(
});
if (userTeam) {
- // User is already in the team
- return res.redirect(`/documents`);
+ console.log("User already in team, redirecting to documents");
+ return res.redirect(`/documents?invitation=teamMember`);
}
- const invitation = await prisma.invitation.findUnique({
- where: {
- email_teamId: {
- email: (session?.user as CustomUser).email!,
+ // Find the invitation
+ let invitation;
+ if (token && email) {
+ // First try to find by token and email
+ invitation = await prisma.invitation.findFirst({
+ where: {
+ token,
+ email,
teamId,
},
- },
- });
+ });
+
+ if (!invitation) {
+ console.log("Invitation not found with token and email");
+ }
+ }
+
+ // If not found by token/email or if token/email not provided, try by user email
+ if (!invitation && userEmail) {
+ invitation = await prisma.invitation.findUnique({
+ where: {
+ email_teamId: {
+ email: userEmail,
+ teamId,
+ },
+ },
+ });
+
+ if (!invitation) {
+ console.log("Invitation not found with user email");
+ }
+ }
if (!invitation) {
return res.status(404).json("Invalid invitation");
@@ -86,7 +128,7 @@ export default async function handle(
},
});
- return res.redirect(`/documents`);
+ return res.redirect(`/documents?invitation=accepted`);
} catch (error) {
errorhandler(error, res);
}
diff --git a/pages/api/teams/[teamId]/invitations/resend.ts b/pages/api/teams/[teamId]/invitations/resend.ts
index 12ef4c55..03213b85 100644
--- a/pages/api/teams/[teamId]/invitations/resend.ts
+++ b/pages/api/teams/[teamId]/invitations/resend.ts
@@ -8,6 +8,7 @@ import { sendTeammateInviteEmail } from "@/lib/emails/send-teammate-invite";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
+import { generateChecksum } from "@/lib/utils/generate-checksum";
export default async function handle(
req: NextApiRequest,
@@ -100,20 +101,40 @@ export default async function handle(
// send invite email
const sender = session.user as CustomUser;
- const params = new URLSearchParams({
- callbackUrl: `${process.env.NEXTAUTH_URL}/api/teams/${teamId}/invitations/accept`,
+ // invitation acceptance URL
+ const invitationUrl = `/api/teams/${teamId}/invitations/accept?token=${invitation.token}&email=${email}`;
+ const fullInvitationUrl = `${process.env.NEXT_PUBLIC_BASE_URL}${invitationUrl}`;
+
+ // magic link
+ const magicLinkParams = new URLSearchParams({
email,
token: invitation.token,
+ callbackUrl: fullInvitationUrl,
});
- const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
+ const magicLink = `${process.env.NEXT_PUBLIC_BASE_URL}/api/auth/callback/email?${magicLinkParams.toString()}`;
+
+ const verifyParams = new URLSearchParams({
+ verification_url: magicLink,
+ email,
+ token: invitation.token,
+ teamId,
+ type: "invitation",
+ expiresAt: expiresAt.toISOString(),
+ });
+
+ const checksum = generateChecksum(magicLink);
+ verifyParams.append("checksum", checksum);
+
+ const verifyUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/verify/invitation?${verifyParams.toString()}`;
+ console.log("verifyUrl", verifyUrl);
sendTeammateInviteEmail({
senderName: sender.name || "",
senderEmail: sender.email || "",
teamName: team?.name || "",
to: email,
- url: url,
+ url: verifyUrl,
});
res.status(200).json("Invitation sent again!");
diff --git a/pages/api/teams/[teamId]/invite.ts b/pages/api/teams/[teamId]/invite.ts
index eb22da61..8c73601f 100644
--- a/pages/api/teams/[teamId]/invite.ts
+++ b/pages/api/teams/[teamId]/invite.ts
@@ -11,6 +11,7 @@ import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
import { authOptions } from "../../auth/[...nextauth]";
+import { generateChecksum } from "@/lib/utils/generate-checksum";
export default async function handle(
req: NextApiRequest,
@@ -131,20 +132,39 @@ export default async function handle(
// send invite email
const sender = session.user as CustomUser;
- const params = new URLSearchParams({
- callbackUrl: `${process.env.NEXTAUTH_URL}/api/teams/${teamId}/invitations/accept`,
+ // invitation acceptance URL
+ const invitationUrl = `/api/teams/${teamId}/invitations/accept?token=${token}&email=${email}`;
+ const fullInvitationUrl = `${process.env.NEXT_PUBLIC_BASE_URL}${invitationUrl}`;
+
+ // magic link
+ const magicLinkParams = new URLSearchParams({
+ email,
+ token,
+ callbackUrl: fullInvitationUrl,
+ });
+
+ const magicLink = `${process.env.NEXT_PUBLIC_BASE_URL}/api/auth/callback/email?${magicLinkParams.toString()}`;
+
+ const verifyParams = new URLSearchParams({
+ verification_url: magicLink,
email,
token,
+ teamId,
+ type: "invitation",
+ expiresAt: expiresAt.toISOString(),
});
- const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
+ const checksum = generateChecksum(magicLink);
+ verifyParams.append("checksum", checksum);
+
+ const verifyUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/verify/invitation?${verifyParams.toString()}`;
sendTeammateInviteEmail({
senderName: sender.name || "",
senderEmail: sender.email || "",
teamName: team?.name || "",
to: email,
- url: url,
+ url: verifyUrl,
});
return res.status(200).json("Invitation sent!");
diff --git a/pages/documents/index.tsx b/pages/documents/index.tsx
index d01c68b0..23d5b243 100644
--- a/pages/documents/index.tsx
+++ b/pages/documents/index.tsx
@@ -1,32 +1,19 @@
import { useTeam } from "@/context/team-context";
import { FolderPlusIcon, PlusIcon } from "lucide-react";
-import { useState } from "react";
-import {
- ChevronLeftIcon,
- ChevronRightIcon,
- ChevronsLeftIcon,
- ChevronsRightIcon,
-} from "lucide-react";
+
import { useRouter } from "next/router";
+import useDocuments, { useRootFolders } from "@/lib/swr/use-documents";
+import { handleInvitationStatus } from "@/lib/utils";
import { AddDocumentModal } from "@/components/documents/add-document-modal";
import { DocumentsList } from "@/components/documents/documents-list";
+import { DocumentsPagination } from "@/components/documents/documents-pagination";
import SortButton from "@/components/documents/filters/sort-button";
import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
import { SearchBoxPersisted } from "@/components/search-box";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-
-import useDocuments, { useRootFolders } from "@/lib/swr/use-documents";
-import { DocumentsPagination } from "@/components/documents/documents-pagination";
export default function Documents() {
const router = useRouter();
@@ -34,6 +21,12 @@ export default function Documents() {
const queryParams = router.query;
const currentPage = Number(queryParams["page"]) || 1;
const pageSize = Number(queryParams["limit"]) || 10;
+ const invitation = queryParams["invitation"] as "accepted" | "teamMember";
+
+ // Handle invitation status
+ if (invitation) {
+ handleInvitationStatus(invitation, queryParams, router);
+ }
const { folders } = useRootFolders();
const { documents, pagination, isValidating, isFiltered } = useDocuments();