Skip to content

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

♻️ Move auth out of user profile mutations into the action layer (#2642)

Luke Vellafde7dfdfcdd8
diff --git a/CLAUDE.md b/CLAUDE.md
index 52a33135d..585e9c794 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -180,8 +180,8 @@ Always use gitmoji prefixes in commit messages. Follow the gitmoji convention (h
**Feature file vocabulary** — closed set; new file names require a team decision. Applies recursively in sub-concern directories:
- `data.ts` — reads (Prisma queries), must start with `import "server-only"`
-- `mutations.ts` — writes + cache invalidation, must start with `import "server-only"`
-- `actions.ts` — `"use server"` actions, thin wrappers over mutations, validated via safe-action + `schema.ts`
+- `mutations.ts` — writes + cache invalidation, must start with `import "server-only"`. Trusts its input: takes explicit parameters (`userId`, not headers), no session reads, no `headers()`, callable from system contexts (webhooks, cron, moderation). Authorization happens in `actions.ts` (safe-action middleware + CASL against the database). Never call Better-Auth endpoints from a mutation — they resolve the target user from request headers and authorize against the session snapshot; use adapter-level APIs (`authLib.$context` → `internalAdapter`) instead
+- `actions.ts` — `"use server"` actions, thin wrappers over mutations, validated via safe-action + `schema.ts`. Owns authentication and authorization (safe-action clients + CASL checks against database state, never against the session snapshot). Exception to the thin-wrapper rule: writes whose target user is defined by the session (self-profile updates) call the Better-Auth endpoint directly in the action — the endpoint refreshes the session snapshot and cookie cache in one step. Rule of thumb: target user from a parameter → mutation via `internalAdapter`; target user from the session → Better-Auth endpoint in the action
- `schema.ts` — Zod schemas (isomorphic, no Prisma imports)
- `types.ts` — domain types
- `ability.ts` — CASL permissions
diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.ts
index 66960f264..54bab9e14 100644
--- a/apps/web/src/features/user/actions.ts
+++ b/apps/web/src/features/user/actions.ts
@@ -3,13 +3,7 @@ import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
import { headers } from "next/headers";
import * as z from "zod";
-import {
- banUser,
- unbanUser,
- updateUserImage,
- updateUserName,
- updateUserRole,
-} from "@/features/user/mutations";
+import { banUser, unbanUser, updateUserRole } from "@/features/user/mutations";
import authLib from "@/lib/auth";
import { timeFormatSchema, weekStartSchema } from "@/lib/datetime/schema";
import { AppError } from "@/lib/errors/app-error";
@@ -24,6 +18,13 @@ import {
} from "@/lib/storage/image-upload";
import { timezoneSchema } from "@/lib/utils/timezone-schema";
+// Self-profile updates call Better-Auth's updateUser endpoint directly
+// instead of going through a mutation: the target user is defined by the
+// session (identity, not a privilege decision), and the endpoint refreshes
+// both the session snapshot in secondary storage and the session cookie
+// cache in one step. Writes that target an arbitrary userId (admin,
+// moderation, system contexts) live in mutations.ts.
+
export const updateUserNameAction = authActionClient
.metadata({ actionName: "update_user_name" })
.inputSchema(
@@ -31,8 +32,11 @@ export const updateUserNameAction = authActionClient
name: z.string().trim().min(1).max(100),
}),
)
- .action(async ({ ctx, parsedInput }) => {
- await updateUserName({ userId: ctx.user.id, name: parsedInput.name });
+ .action(async ({ parsedInput }) => {
+ await authLib.api.updateUser({
+ body: { name: parsedInput.name },
+ headers: await headers(),
+ });
});
export const updateLocalizationAction = authActionClient
@@ -92,7 +96,10 @@ export const updateUserAvatarAction = authActionClient
const oldImageKey = ctx.user.image;
- await updateUserImage({ userId: ctx.user.id, image: imageKey });
+ await authLib.api.updateUser({
+ body: { image: imageKey },
+ headers: await headers(),
+ });
// Only delete from storage if it's an internal avatar, not an external
// URL from an OAuth provider.
@@ -106,7 +113,10 @@ export const removeUserAvatarAction = authActionClient
.action(async ({ ctx }) => {
const oldImageKey = ctx.user.image;
- await updateUserImage({ userId: ctx.user.id, image: null });
+ await authLib.api.updateUser({
+ body: { image: null },
+ headers: await headers(),
+ });
// Only delete from storage if it's an internal avatar, not an external
// URL from an OAuth provider.
diff --git a/apps/web/src/features/user/constants.ts b/apps/web/src/features/user/constants.ts
deleted file mode 100644
index b754e6e90..000000000
--- a/apps/web/src/features/user/constants.ts
+++ /dev/null
@@ -1 +0,0 @@
-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 6b02e87c6..71f995e84 100644
--- a/apps/web/src/features/user/mutations.ts
+++ b/apps/web/src/features/user/mutations.ts
@@ -2,9 +2,6 @@ import "server-only";
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({
@@ -43,41 +40,12 @@ 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");
-}
+// There are deliberately no self-profile mutations (name, image,
+// localization) here. Writes whose target user is defined by the session
+// belong in actions.ts, where they call Better-Auth's updateUser endpoint
+// directly — it refreshes the session snapshot in secondary storage and the
+// session cookie cache in one step. Mutations only hold writes that target
+// an arbitrary userId.
// Role changes must go through Better-Auth's internal adapter so the user
// snapshot cached in each session (secondary storage) gets refreshed — a bare