Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

🐛 Refresh session caches when a user updates their profile (#2431)

Luke Vella25aeaee4ab26
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/profile-picture.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/profile-picture.tsx
index d254a26a0..a7b2e4fd8 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/profile-picture.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/profile-picture.tsx
@@ -1,14 +1,18 @@
"use client";
-import { useRouter } from "next/navigation";
import {
ImageUpload,
ImageUploadControl,
ImageUploadPreview,
} from "@/components/image-upload";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
+import {
+ getAvatarUploadUrlAction,
+ removeUserAvatarAction,
+ updateUserAvatarAction,
+} from "@/features/user/actions";
import { useFeatureFlag } from "@/lib/feature-flags/client";
-import { trpc } from "@/trpc/client";
+import { useSafeAction } from "@/lib/safe-action/client";
function ProfilePictureUpload({
image,
@@ -17,20 +21,16 @@ function ProfilePictureUpload({
image?: string;
name: string;
}) {
- const router = useRouter();
-
- const getAvatarUploadUrl = trpc.user.getAvatarUploadUrl.useMutation();
- const updateAvatar = trpc.user.updateAvatar.useMutation();
- const removeAvatar = trpc.user.removeAvatar.useMutation();
+ const getAvatarUploadUrl = useSafeAction(getAvatarUploadUrlAction);
+ const updateUserAvatar = useSafeAction(updateUserAvatarAction);
+ const removeUserAvatar = useSafeAction(removeUserAvatarAction);
const handleUploadSuccess = async (imageKey: string) => {
- await updateAvatar.mutateAsync({ imageKey });
- router.refresh();
+ await updateUserAvatar.executeAsync({ imageKey });
};
const handleRemoveSuccess = async () => {
- await removeAvatar.mutateAsync();
- router.refresh();
+ await removeUserAvatar.executeAsync();
};
return (
@@ -39,7 +39,13 @@ function ProfilePictureUpload({
<OptimizedAvatarImage src={image} name={name} size="xl" />
</ImageUploadPreview>
<ImageUploadControl
- getUploadUrl={(input) => getAvatarUploadUrl.mutateAsync(input)}
+ getUploadUrl={async (input) => {
+ const result = await getAvatarUploadUrl.executeAsync(input);
+ if (!result?.data) {
+ throw new Error("Failed to get upload URL");
+ }
+ return result.data;
+ }}
onUploadSuccess={handleUploadSuccess}
onRemoveSuccess={handleRemoveSuccess}
hasCurrentImage={!!image}
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/profile-settings.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/profile-settings.tsx
index 46bcb916b..d82d864c8 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/profile-settings.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/profile-settings.tsx
@@ -10,11 +10,12 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
-import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import * as z from "zod";
+import { updateUserNameAction } from "@/features/user/actions";
import { Trans } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
import { trpc } from "@/trpc/client";
import { ProfilePicture } from "./profile-picture";
@@ -26,8 +27,7 @@ const profileSettingsFormData = z.object({
export const ProfileSettings = () => {
const [user] = trpc.user.getAuthed.useSuspenseQuery();
- const changeName = trpc.user.changeName.useMutation();
- const router = useRouter();
+ const updateUserName = useSafeAction(updateUserNameAction);
const form = useForm({
defaultValues: {
name: user.name,
@@ -42,10 +42,9 @@ export const ProfileSettings = () => {
<form
onSubmit={handleSubmit(async (data) => {
if (data.name !== user.name) {
- await changeName.mutateAsync({ name: data.name });
+ await updateUserName.executeAsync({ name: data.name });
}
reset(data);
- router.refresh();
})}
>
<div className="flex flex-col gap-y-4">
diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.ts
index 449d90061..d465d7f91 100644
--- a/apps/web/src/features/user/actions.ts
+++ b/apps/web/src/features/user/actions.ts
@@ -2,8 +2,90 @@
import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
import * as z from "zod";
+import { updateUserImage, updateUserName } from "@/features/user/mutations";
import { AppError } from "@/lib/errors";
-import { adminActionClient } from "@/lib/safe-action/server";
+import {
+ adminActionClient,
+ authActionClient,
+ createRateLimitMiddleware,
+} from "@/lib/safe-action/server";
+import {
+ deleteImageFromS3,
+ getImageUploadUrl,
+} from "@/lib/storage/image-upload";
+
+export const updateUserNameAction = authActionClient
+ .metadata({ actionName: "update_user_name" })
+ .inputSchema(
+ z.object({
+ name: z.string().trim().min(1).max(100),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ await updateUserName({ userId: ctx.user.id, name: parsedInput.name });
+ });
+
+export const getAvatarUploadUrlAction = authActionClient
+ .metadata({ actionName: "get_avatar_upload_url" })
+ .use(createRateLimitMiddleware(10, "1 h"))
+ .inputSchema(
+ z.object({
+ fileType: z.enum(["image/jpeg", "image/png"]),
+ fileSize: z.number(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ return await getImageUploadUrl({
+ keyPrefix: "avatars",
+ entityId: ctx.user.id,
+ fileType: parsedInput.fileType,
+ fileSize: parsedInput.fileSize,
+ });
+ });
+
+export const updateUserAvatarAction = authActionClient
+ .metadata({ actionName: "update_user_avatar" })
+ .inputSchema(
+ z.object({
+ imageKey: z.string().max(255),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ const { imageKey } = parsedInput;
+
+ if (!imageKey.startsWith(`avatars/${ctx.user.id}-`)) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "Invalid image key",
+ });
+ }
+
+ const oldImageKey = ctx.user.image;
+
+ await updateUserImage({ userId: ctx.user.id, image: imageKey });
+
+ // Only delete from storage if it's an internal avatar, not an external
+ // URL from an OAuth provider.
+ if (oldImageKey && !oldImageKey.startsWith("https://")) {
+ await deleteImageFromS3(oldImageKey);
+ }
+ });
+
+export const removeUserAvatarAction = authActionClient
+ .metadata({ actionName: "remove_user_avatar" })
+ .action(async ({ ctx }) => {
+ const oldImageKey = ctx.user.image;
+
+ await updateUserImage({ userId: ctx.user.id, image: null });
+
+ // Only delete from storage if it's an internal avatar, not an external
+ // URL from an OAuth provider.
+ const isInternalAvatar = oldImageKey && !oldImageKey.startsWith("https://");
+
+ if (isInternalAvatar) {
+ await deleteImageFromS3(oldImageKey);
+ }
+ });
export const changeRoleAction = adminActionClient
.metadata({ actionName: "change_role" })
diff --git a/apps/web/src/features/user/constants.ts b/apps/web/src/features/user/constants.ts
new file mode 100644
index 000000000..b754e6e90
--- /dev/null
+++ b/apps/web/src/features/user/constants.ts
@@ -0,0 +1 @@
+export const userProfileTag = (userId: string) => `user-profile:${userId}`;
diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.ts
index be40c823d..7595c132b 100644
--- a/apps/web/src/features/user/mutations.ts
+++ b/apps/web/src/features/user/mutations.ts
@@ -1,5 +1,9 @@
import type { TimeFormat } from "@rallly/database";
import { prisma } from "@rallly/database";
+import { revalidateTag } from "next/cache";
+import { headers } from "next/headers";
+import { userProfileTag } from "@/features/user/constants";
+import { authLib } from "@/lib/auth";
export async function createUser({
name,
@@ -37,6 +41,42 @@ export async function createUser({
return user;
}
+// Profile updates must go through Better-Auth rather than Prisma so that the
+// session cookie cache and the cached session data in secondary storage get
+// refreshed. Better-Auth always updates the user tied to the session in
+// `headers`, so `userId` must be the current user's id (it scopes the cache
+// tag).
+
+export async function updateUserName({
+ userId,
+ name,
+}: {
+ userId: string;
+ name: string;
+}) {
+ await authLib.api.updateUser({
+ body: { name },
+ headers: await headers(),
+ });
+
+ revalidateTag(userProfileTag(userId), "max");
+}
+
+export async function updateUserImage({
+ userId,
+ image,
+}: {
+ userId: string;
+ image: string | null;
+}) {
+ await authLib.api.updateUser({
+ body: { image },
+ headers: await headers(),
+ });
+
+ revalidateTag(userProfileTag(userId), "max");
+}
+
export async function setActiveSpace({
userId,
spaceId,
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index c9f798898..9e69102b2 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -7,6 +7,7 @@ import type { BetterAuthPlugin } from "better-auth";
import { APIError, betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { createAuthMiddleware } from "better-auth/api";
+import { nextCookies } from "better-auth/next-js";
import {
admin,
anonymous,
@@ -172,6 +173,9 @@ export const authLib = betterAuth({
}),
...conditionalPlugins,
hostOnlyCookieCleanup,
+ // Must be last — applies Set-Cookie headers from auth.api calls made in
+ // server actions and route handlers.
+ nextCookies(),
],
socialProviders: {
google:
diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.ts
index 1da56b9f3..94defb034 100644
--- a/apps/web/src/trpc/routers/user.ts
+++ b/apps/web/src/trpc/routers/user.ts
@@ -12,10 +12,6 @@ import { defaultNotificationPreferences } from "@/features/notifications/constan
import { getNotificationPreferences } from "@/features/notifications/queries";
import { activityEventTypes } from "@/features/notifications/schema";
import { defineAbilityFor } from "@/features/user/ability";
-import {
- deleteImageFromS3,
- getImageUploadUrl,
-} from "@/lib/storage/image-upload";
import { createToken } from "@/utils/session";
import { timezoneSchema } from "@/utils/timezone-schema";
import {
@@ -36,22 +32,6 @@ export const user = router({
getAuthed: privateProcedure.query(async ({ ctx }) => {
return ctx.user;
}),
- changeName: privateProcedure
- .input(
- z.object({
- name: z.string().min(1).max(100),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await prisma.user.update({
- where: {
- id: ctx.user.id,
- },
- data: {
- name: input.name,
- },
- });
- }),
updatePreferences: privateProcedure
.input(
z.object({
@@ -141,67 +121,6 @@ export const user = router({
return { success: true as const };
}),
- getAvatarUploadUrl: privateProcedure
- .use(createRateLimitMiddleware("get_avatar_upload_url", 10, "1 h"))
- .input(
- z.object({
- fileType: z.enum(["image/jpeg", "image/png"]),
- fileSize: z.number(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- return await getImageUploadUrl({
- keyPrefix: "avatars",
- entityId: ctx.user.id,
- fileType: input.fileType,
- fileSize: input.fileSize,
- });
- }),
- updateAvatar: privateProcedure
- .input(z.object({ imageKey: z.string().max(255) }))
- .mutation(async ({ ctx, input }) => {
- const userId = ctx.user.id;
-
- const expectedPrefix = `avatars/${userId}-`;
- if (!input.imageKey.startsWith(expectedPrefix)) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Invalid image key",
- });
- }
-
- const oldImageKey = ctx.user.image;
-
- await prisma.user.update({
- where: { id: userId },
- data: { image: input.imageKey },
- });
-
- // Delete old image from S3 if it exists
- if (oldImageKey) {
- await deleteImageFromS3(oldImageKey);
- }
-
- return { success: true };
- }),
- removeAvatar: privateProcedure.mutation(async ({ ctx }) => {
- const userId = ctx.user.id;
- const oldImageKey = ctx.user.image;
-
- await prisma.user.update({
- where: { id: userId },
- data: { image: null },
- });
-
- // Delete the avatar from storage if it's an internal avatar
- const isInternalAvatar = oldImageKey && !oldImageKey.startsWith("https://");
-
- if (isInternalAvatar) {
- await deleteImageFromS3(oldImageKey);
- }
-
- return { success: true };
- }),
deleteMe: privateProcedure.mutation(async ({ ctx }) => {
const userId = ctx.user.id;