Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🐛 Fix user can’t edit participant when session expires (#2066)
Luke Vella7e044440f28f
diff --git a/apps/web/src/components/discussion/discussion.tsx b/apps/web/src/components/discussion/discussion.tsxindex 88b6fe974..d25a8ec45 100644--- a/apps/web/src/components/discussion/discussion.tsx+++ b/apps/web/src/components/discussion/discussion.tsx@@ -30,6 +30,7 @@ import { Controller, useForm } from "react-hook-form";import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";import { Participant, ParticipantName } from "@/components/participant";import { useParticipants } from "@/components/participants-provider";+import { useEditToken } from "@/components/poll/mutations";import { Trans } from "@/components/trans";import { usePoll } from "@/contexts/poll";import { useRole } from "@/contexts/role";@@ -148,6 +149,7 @@ function DiscussionInner() {const poll = usePoll();const pollId = poll.id;+ const token = useEditToken();const { data: comments } = trpc.polls.comments.list.useQuery({ pollId });@@ -218,6 +220,7 @@ function DiscussionInner() {onClick={() => {deleteComment.mutate({commentId: comment.id,+ token,});}}>diff --git a/apps/web/src/components/participant-dropdown.tsx b/apps/web/src/components/participant-dropdown.tsxindex fecbf1ac8..e63c0260c 100644--- a/apps/web/src/components/participant-dropdown.tsx+++ b/apps/web/src/components/participant-dropdown.tsx@@ -35,7 +35,10 @@ import { useForm } from "react-hook-form";import { useMount } from "react-use";import { z } from "zod";-import { useDeleteParticipantMutation } from "@/components/poll/mutations";+import {+ useDeleteParticipantMutation,+ useEditToken,+} from "@/components/poll/mutations";import { Trans } from "@/components/trans";import { useTranslation } from "@/i18n/client";import { trpc } from "@/trpc/client";@@ -136,6 +139,7 @@ const DeleteParticipantModal = ({participantName: string;}) => {const deleteParticipant = useDeleteParticipantMutation();+ const token = useEditToken();return (<Dialog open={open} onOpenChange={onOpenChange}><DialogContent>@@ -164,6 +168,7 @@ const DeleteParticipantModal = ({onClick={async () => {deleteParticipant.mutate({participantId,+ token,});onOpenChange(false);}}@@ -191,6 +196,7 @@ const ChangeNameModal = (props: {onOpenChange: (open: boolean) => void;}) => {const posthog = usePostHog();+ const token = useEditToken();const changeName = trpc.polls.participants.rename.useMutation({onSuccess: (_, { participantId, newName }) => {posthog?.capture("changed name", {@@ -215,18 +221,21 @@ const ChangeNameModal = (props: {});});+ const { participantId, onOpenChange } = props;+const handler = React.useCallback<SubmitHandler<ChangeNameForm>>(async ({ name }) => {if (formState.isDirty) {// change nameawait changeName.mutateAsync({- participantId: props.participantId,+ participantId,newName: name,+ token,});}- props.onOpenChange(false);+ onOpenChange(false);},- [changeName, formState.isDirty, props],+ [changeName, formState.isDirty, participantId, token, onOpenChange],);const { requiredString } = useFormValidation();diff --git a/apps/web/src/components/poll/mutations.ts b/apps/web/src/components/poll/mutations.tsindex aef240bd2..63a1066f5 100644--- a/apps/web/src/components/poll/mutations.ts+++ b/apps/web/src/components/poll/mutations.ts@@ -1,4 +1,5 @@import { toast } from "@rallly/ui/sonner";+import { useSearchParams } from "next/navigation";import { usePoll } from "@/components/poll-context";import { trpc } from "@/trpc/client";import type { ParticipantForm } from "./types";@@ -13,6 +14,11 @@ export const normalizeVotes = (}));};+export const useEditToken = () => {+ const searchParams = useSearchParams();+ return searchParams.get("token") ?? undefined;+};+export const useAddParticipantMutation = () => {return trpc.polls.participants.add.useMutation();};diff --git a/apps/web/src/components/poll/voting-form.tsx b/apps/web/src/components/poll/voting-form.tsxindex 211599983..19af1f3e0 100644--- a/apps/web/src/components/poll/voting-form.tsx+++ b/apps/web/src/components/poll/voting-form.tsx@@ -14,6 +14,7 @@ import { NewParticipantForm } from "@/components/new-participant-modal";import { useParticipants } from "@/components/participants-provider";import {normalizeVotes,+ useEditToken,useUpdateParticipantMutation,} from "@/components/poll/mutations";import { Trans } from "@/components/trans";@@ -82,6 +83,7 @@ export const useVotingForm = () => {export const VotingForm = ({ children }: React.PropsWithChildren) => {const { id: pollId, options } = usePoll();const updateParticipant = useUpdateParticipantMutation();+ const token = useEditToken();const { participants } = useParticipants();const { canAddNewParticipant, canEditParticipant } = usePermissions();@@ -124,6 +126,7 @@ export const VotingForm = ({ children }: React.PropsWithChildren) => {participantId: data.participantId,pollId,votes: normalizeVotes(optionIds, data.votes),+ token,});form.reset({diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.tsindex 21579bd4a..2236e77c2 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -12,6 +12,7 @@ import {router,} from "../../trpc";import type { DisableNotificationsPayload } from "../../types";+import { resolveUserId } from "./utils";export const comments = router({list: publicProcedure@@ -189,10 +190,12 @@ export const comments = router({.input(z.object({commentId: z.string(),+ token: z.string().optional(),}),)- .use(requireUserMiddleware)- .mutation(async ({ input: { commentId }, ctx }) => {+ .mutation(async ({ input: { commentId, token }, ctx }) => {+ const userId = await resolveUserId(token, ctx.user);+const comment = await prisma.comment.findUnique({where: { id: commentId },select: { pollId: true, userId: true, guestId: true },@@ -205,13 +208,9 @@ export const comments = router({});}- const isAuthor =- comment.userId === ctx.user.id || comment.guestId === ctx.user.id;+ const isAuthor = comment.userId === userId || comment.guestId === userId;- if (- !isAuthor &&- !(await hasPollAdminAccess(comment.pollId, ctx.user.id))- ) {+ if (!isAuthor && !(await hasPollAdminAccess(comment.pollId, userId))) {throw new TRPCError({code: "FORBIDDEN",message: "You are not allowed to delete this comment",@@ -227,7 +226,7 @@ export const comments = router({// Track comment deletion analyticsif (comment) {ctx.posthog?.capture({- distinctId: ctx.user.id,+ distinctId: userId,event: "poll_comment_delete",groups: {poll: comment.pollId,diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.tsindex 4a3da00e0..57d980110 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -7,7 +7,6 @@ import { z } from "zod";import { hasPollAdminAccess } from "@/features/poll/query";import { getEmailClient } from "@/utils/emails";import { createToken } from "@/utils/session";-import {createRateLimitMiddleware,publicProcedure,@@ -15,6 +14,7 @@ import {router,} from "../../trpc";import type { DisableNotificationsPayload } from "../../types";+import { createParticipantEditToken, resolveUserId } from "./utils";const MAX_PARTICIPANTS = 1000;@@ -167,14 +167,13 @@ export const participants = router({.input(z.object({participantId: z.string(),+ token: z.string().optional(),}),)- .use(requireUserMiddleware)- .mutation(async ({ input: { participantId }, ctx }) => {- const participant = await canModifyParticipant(- participantId,- ctx.user.id,- );+ .mutation(async ({ input: { participantId, token }, ctx }) => {+ const userId = await resolveUserId(token, ctx.user);++ const participant = await canModifyParticipant(participantId, userId);await prisma.participant.update({where: {@@ -187,7 +186,7 @@ export const participants = router({});ctx.posthog?.capture({- distinctId: ctx.user.id,+ distinctId: userId,event: "poll_response_delete",properties: {participant_id: participant.id,@@ -286,12 +285,7 @@ export const participants = router({);if (email) {- const token = await createToken(- { userId: ctx.user.id },- {- ttl: 0, // basically forever- },- );+ const token = await createParticipantEditToken(ctx.user.id);getEmailClient(ctx.user.locale).queueTemplate("NewParticipantConfirmationEmail",@@ -342,10 +336,17 @@ export const participants = router({},),rename: publicProcedure- .input(z.object({ participantId: z.string(), newName: z.string() }))- .use(requireUserMiddleware)- .mutation(async ({ input: { participantId, newName }, ctx }) => {- await canModifyParticipant(participantId, ctx.user.id);+ .input(+ z.object({+ participantId: z.string(),+ newName: z.string().min(1, "Participant name is required").max(100),+ token: z.string().optional(),+ }),+ )+ .mutation(async ({ input: { participantId, newName, token }, ctx }) => {+ const userId = await resolveUserId(token, ctx.user);++ await canModifyParticipant(participantId, userId);await prisma.participant.update({where: {@@ -368,13 +369,15 @@ export const participants = router({type: z.enum(["yes", "no", "ifNeedBe"]),}).array(),+ token: z.string().optional(),}),)- .use(requireUserMiddleware)- .mutation(async ({ input: { participantId, votes }, ctx }) => {+ .mutation(async ({ input: { participantId, votes, token }, ctx }) => {+ const userId = await resolveUserId(token, ctx.user);+const existingParticipant = await canModifyParticipant(participantId,- ctx.user.id,+ userId,);const pollId = existingParticipant.pollId;@@ -424,7 +427,7 @@ export const participants = router({});ctx.posthog?.capture({- distinctId: ctx.user.id,+ distinctId: userId,event: "poll_response_update",groups: {poll: pollId,diff --git a/apps/web/src/trpc/routers/polls/utils.ts b/apps/web/src/trpc/routers/polls/utils.tsnew file mode 100644index 000000000..808dcaf53--- /dev/null+++ b/apps/web/src/trpc/routers/polls/utils.ts@@ -0,0 +1,39 @@+import { TRPCError } from "@trpc/server";+import { createToken, decryptToken } from "@/utils/session";++export async function getUserIdFromToken(+ token: string | undefined,+): Promise<string | null> {+ if (!token) {+ return null;+ }++ const payload = await decryptToken<{ userId: string }>(token);+ return payload?.userId ?? null;+}++export async function createParticipantEditToken(+ userId: string,+): Promise<string> {+ return await createToken(+ { userId },+ {+ ttl: 0, // basically forever+ },+ );+}++export async function resolveUserId(+ token: string | undefined,+ ctxUser: { id: string } | undefined,+): Promise<string> {+ const userIdFromToken = await getUserIdFromToken(token);+ const userId = userIdFromToken ?? ctxUser?.id;+ if (!userId) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "This method requires a user or valid token",+ });+ }+ return userId;+}