Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: improve team member invitation flow
Marc Seitz6bdcccc15050
diff --git a/components/emails/team-invitation.tsx b/components/emails/team-invitation.tsxindex eb8810e3..5dabf9ae 100644--- a/components/emails/team-invitation.tsx+++ b/components/emails/team-invitation.tsx@@ -16,14 +16,12 @@ export default function TeamInvitation({senderName,senderEmail,teamName,- teamId,- token,+ url,}: {senderName: string;senderEmail: string;teamName: string;- teamId: string;- token: string;+ url: string;}) {return (<Html>@@ -48,7 +46,7 @@ export default function TeamInvitation({<Section className="text-center mt-[32px] mb-[32px]"><ButtonclassName="bg-black rounded text-white text-xs font-semibold no-underline text-center"- href={`${process.env.NEXT_PUBLIC_BASE_URL}/api/teams/${teamId}/invite?token=${token}`}+ href={`${url}`}style={{ padding: "12px 20px" }}>Join the team@@ -56,7 +54,7 @@ export default function TeamInvitation({</Section><Text className="text-sm text-black">or copy and paste this URL into your browser: <br />- {`${process.env.NEXT_PUBLIC_BASE_URL}/api/teams/${teamId}/invite?token=${token}`}+ {`${url}`}</Text><Text className="text-sm text-gray-400">Marc from Papermark</Text><Hr />diff --git a/lib/api/auth/token.ts b/lib/api/auth/token.tsnew file mode 100644index 00000000..acbd622e--- /dev/null+++ b/lib/api/auth/token.ts@@ -0,0 +1,14 @@+import { createHash } from "crypto";++export const hashToken = (+ token: string,+ {+ noSecret = false,+ }: {+ noSecret?: boolean;+ } = {},+) => {+ return createHash("sha256")+ .update(`${token}${noSecret ? "" : process.env.NEXTAUTH_SECRET}`)+ .digest("hex");+};diff --git a/lib/emails/send-teammate-invite.ts b/lib/emails/send-teammate-invite.tsindex 553b6267..adbefc65 100644--- a/lib/emails/send-teammate-invite.ts+++ b/lib/emails/send-teammate-invite.ts@@ -5,16 +5,14 @@ export const sendTeammateInviteEmail = async ({senderName,senderEmail,teamName,- teamId,- token,to,+ url,}: {senderName: string;senderEmail: string;teamName: string;- teamId: string;- token: string;to: string;+ url: string;}) => {await sendEmail({to: to,@@ -23,8 +21,7 @@ export const sendTeammateInviteEmail = async ({senderName,senderEmail,teamName,- teamId,- token,+ url,}),test: process.env.NODE_ENV === "development",system: true,diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].tsindex 98c274f2..2f253f54 100644--- a/pages/api/auth/[...nextauth].ts+++ b/pages/api/auth/[...nextauth].ts@@ -51,6 +51,7 @@ export const authOptions: NextAuthOptions = {EmailProvider({async sendVerificationRequest({ identifier, url }) {if (process.env.NODE_ENV === "development") {+ console.log("[Login URL]", url);return;} else {await sendVerificationRequestEmail({diff --git a/pages/api/teams/[teamId]/invitations/accept.ts b/pages/api/teams/[teamId]/invitations/accept.tsnew file mode 100644index 00000000..87f3d580--- /dev/null+++ b/pages/api/teams/[teamId]/invitations/accept.ts@@ -0,0 +1,85 @@+import { getServerSession } from "next-auth";+import { NextApiRequest, NextApiResponse } from "next";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { errorhandler } from "@/lib/errorHandler";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/invitations/accept+ const session = await getServerSession(req, res, authOptions);++ const { teamId } = req.query as { teamId: string };++ if (!session) {+ res.redirect(`/login?next=/api/teams/${teamId}/invitations/accept`);+ return;+ }++ const userId = (session.user as CustomUser).id;++ try {+ const userTeam = await prisma.userTeam.findFirst({+ where: {+ teamId,+ userId,+ },+ });++ if (userTeam) {+ // User is already in the team+ return res.redirect(`/documents`);+ }++ const invitation = await prisma.invitation.findUnique({+ where: {+ email_teamId: {+ email: (session?.user as CustomUser).email!,+ teamId,+ },+ },+ });++ if (!invitation) {+ return res.status(404).json("Invalid invitation");+ }++ if (invitation.email !== (session?.user as CustomUser).email) {+ return res.status(403).json("You are not invited to this team");+ }++ const currentTime = new Date();+ if (currentTime > invitation.expires) {+ return res.status(410).json("Invitation link has expired");+ }++ await prisma.team.update({+ where: {+ id: teamId,+ },+ data: {+ users: {+ create: {+ userId,+ },+ },+ },+ });++ // delete the invitation record after user is successfully added to the team+ await prisma.invitation.delete({+ where: {+ token: invitation.token,+ },+ });++ return res.redirect(`/documents`);+ } catch (error) {+ errorhandler(error, res);+ }+ }+}diff --git a/pages/api/teams/[teamId]/invitations/resend.ts b/pages/api/teams/[teamId]/invitations/resend.tsindex c30dd553..44d853cc 100644--- a/pages/api/teams/[teamId]/invitations/resend.ts+++ b/pages/api/teams/[teamId]/invitations/resend.ts@@ -5,7 +5,7 @@ import { CustomUser } from "@/lib/types";import { errorhandler } from "@/lib/errorHandler";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { sendTeammateInviteEmail } from "@/lib/emails/send-teammate-invite";-import { newId } from "@/lib/id-helper";+import { hashToken } from "@/lib/api/auth/token";export default async function handle(req: NextApiRequest,@@ -72,16 +72,46 @@ export default async function handle(},});+ const verificationTokenRecord = await prisma.verificationToken.findUnique(+ {+ where: { token: hashToken(invitation.token) },+ },+ );++ if (!verificationTokenRecord) {+ await prisma.verificationToken.create({+ data: {+ expires: expiresAt,+ token: hashToken(invitation.token),+ identifier: email,+ },+ });+ } else {+ await prisma.verificationToken.update({+ where: { token: hashToken(invitation.token) },+ data: {+ expires: expiresAt,+ },+ });+ }+// send invite emailconst sender = session.user as CustomUser;+ const params = new URLSearchParams({+ callbackUrl: `${process.env.NEXTAUTH_URL}/api/teams/${teamId}/invitations/accept`,+ email,+ token: invitation.token,+ });++ const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;+sendTeammateInviteEmail({senderName: sender.name || "",senderEmail: sender.email || "",teamName: team?.name || "",- teamId: teamId || "",- token: invitation?.token || "",to: email,+ url: url,});res.status(200).json("Invitation sent again!");diff --git a/pages/api/teams/[teamId]/invite.ts b/pages/api/teams/[teamId]/invite.tsindex 01fd0695..40b1d0fc 100644--- a/pages/api/teams/[teamId]/invite.ts+++ b/pages/api/teams/[teamId]/invite.ts@@ -6,6 +6,7 @@ import { CustomUser } from "@/lib/types";import { errorhandler } from "@/lib/errorHandler";import { sendTeammateInviteEmail } from "@/lib/emails/send-teammate-invite";import { newId } from "@/lib/id-helper";+import { hashToken } from "@/lib/api/auth/token";export default async function handle(req: NextApiRequest,@@ -97,93 +98,36 @@ export default async function handle(},});+ await prisma.verificationToken.create({+ data: {+ token: hashToken(token),+ identifier: email,+ expires: expiresAt,+ },+ });+// send invite emailconst sender = session.user as CustomUser;+ const params = new URLSearchParams({+ callbackUrl: `${process.env.NEXTAUTH_URL}/api/teams/${teamId}/invitations/accept`,+ email,+ token,+ });++ const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;+sendTeammateInviteEmail({senderName: sender.name || "",senderEmail: sender.email || "",teamName: team?.name || "",- teamId: team?.id || "",- token,to: email,+ url: url,});return res.status(200).json("Invitation sent!");} catch (error) {errorhandler(error, res);}- } else if (req.method === "GET") {- // GET /api/teams/:teamId/invite- const session = await getServerSession(req, res, authOptions);-- const { token, teamId } = req.query as {- token: string;- teamId: string;- };-- if (!session) {- res.redirect(`/login?next=/api/teams/${teamId}/invite?token=${token}`);- return;- }-- const userId = (session.user as CustomUser).id;-- try {- const userTeam = await prisma.userTeam.findFirst({- where: {- teamId,- userId,- },- });-- if (userTeam) {- // User is already in the team- return res.redirect(`/documents`);- }-- const invitation = await prisma.invitation.findUnique({- where: {- token,- },- });-- if (!invitation) {- return res.status(400).json("Invalid invitation token");- }-- if (invitation.email !== (session?.user as CustomUser).email) {- return res.status(403).json("You are not invited to this team");- }-- const currentTime = new Date();- if (currentTime > invitation.expires) {- return res.status(400).json("Invitation link has expired");- }-- await prisma.team.update({- where: {- id: teamId,- },- data: {- users: {- create: {- userId,- },- },- },- });-- // delete the invitation record after user is successfully added to the team- await prisma.invitation.delete({- where: {- token,- },- });-- return res.redirect("/documents");- } catch (error) {- errorhandler(error, res);- }}}