Leaf and Kettle's profile page has a form with two fields, a name and a newsletter checkbox, run through useActionState by updateProfile in app/account/actions.ts. The first version, in the starter, wrote the whole form to the database. A customer who added <input name="role" value="staff"> to the page with the browser's dev tools became staff. That bug is called mass assignment. Rewrite the Server Action.
A Server Action is a public endpoint: anyone can post it any fields, whatever the form shows. Ask who's posting with getViewer() from @/lib/session, which gives { id, role } or null; with null, throw an Error with the message Sign in to change your profile.. The profile to change is always the viewer's own: an old version of the form also sends a hidden userId field, and that's ignored like every other field you don't read.
Read only the two fields. name is trimmed and must be 1 to 40 characters; otherwise return { error: "Enter a name of up to 40 characters.", name } with the trimmed name, and save nothing. A ticked newsletter checkbox is sent as on, and an unticked one isn't sent at all.
Save them with updateUser(viewer.id, { name, newsletter }) from @/lib/users, which writes every key it's given, call revalidatePath("/account/profile"), and return { error: null, name }. Everything an action returns is sent to the browser, so don't return the row updateUser gives back: it holds the email, the store credit, and the password hash.
Cookie: session=token-ana
name " Ana Lima-Souza ", newsletter "on", role "staff", storeCredit "9999", userId "u_ben"
→ updateUser("u_ana", { name: "Ana Lima-Souza", newsletter: true })
→ { error: null, name: "Ana Lima-Souza" }
lib/session.ts, read-only. Import it as @/lib/session.
import { cookies } from "next/headers";
export type Viewer = { id: string; role: "customer" | "staff" };
/** Live sessions: the token in the `session` cookie, and whose it is. */
const sessions = new Map<string, Viewer>([
["token-ana", { id: "u_ana", role: "customer" }],
["token-ben", { id: "u_ben", role: "customer" }],
["token-sam", { id: "u_sam", role: "staff" }],
]);
/** Who sent this request, from the `session` cookie, or null for a guest. */
export async function getViewer(): Promise<Viewer | null> {
const token = (await cookies()).get("session")?.value;
const viewer = token ? sessions.get(token) : undefined;
return viewer ? { ...viewer } : null;
}
lib/users.ts, read-only. Import it as @/lib/users.
export type User = {
id: string;
name: string;
email: string;
role: "customer" | "staff";
newsletter: boolean;
storeCredit: number;
passwordHash: string;
};
/** Every account: a stand-in for the shop's database. */
export const users: User[] = [
{
id: "u_ana",
name: "Ana Lima",
email: "ana@example.com",
role: "customer",
newsletter: false,
storeCredit: 0,
passwordHash: "$argon2id$v=19$m=65536,t=3,p=4$c2FsdC1hbmE$aGFzaC1hbmE",
},
{
id: "u_ben",
name: "Ben Okafor",
email: "ben@example.com",
role: "customer",
newsletter: true,
storeCredit: 500,
passwordHash: "$argon2id$v=19$m=65536,t=3,p=4$c2FsdC1iZW4$aGFzaC1iZW4",
},
];
/**
* Writes `changes` onto the user's row, every key as given, like an ORM's update, and returns the
* whole row as saved. Undefined when there's no such user.
*/
export async function updateUser(id: string, changes: Partial<User>): Promise<User | undefined> {
const user = users.find((entry) => entry.id === id);
if (!user) return undefined;
Object.assign(user, changes);
return { ...user };
}
const initial = { error: null, name: "" };
const save = (token, fields) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, () => updateProfile(initial, formData(fields)));
const ana = () => users.find((user) => user.id === "u_ana");
const ben = () => users.find((user) => user.id === "u_ben");
const before = { ...ana() };
expect(await save("token-ana", { name: " Ana Lima-Souza ", newsletter: "on" })).toEqual({ error: null, name: "Ana Lima-Souza" });
expect(ana()).toEqual({ ...before, name: "Ana Lima-Souza", newsletter: true });
expect(cache.revalidatedPaths).toEqual(["/account/profile"]);
const initial = { error: null, name: "" };
const save = (token, fields) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, () => updateProfile(initial, formData(fields)));
const ana = () => users.find((user) => user.id === "u_ana");
const ben = () => users.find((user) => user.id === "u_ben");
const before = { ...ben() };
expect(await save("token-ben", { name: "Ben Okafor" })).toEqual({ error: null, name: "Ben Okafor" });
expect(ben()).toEqual({ ...before, newsletter: false });
const initial = { error: null, name: "" };
const save = (token, fields) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, () => updateProfile(initial, formData(fields)));
const ana = () => users.find((user) => user.id === "u_ana");
const ben = () => users.find((user) => user.id === "u_ben");
const before = { ...ana() };
const answer = await save("token-ana", {
name: "Ana",
newsletter: "on",
role: "staff",
storeCredit: "9999",
email: "ana@evil.example",
passwordHash: "x",
id: "u_sam",
isAdmin: "true",
});
expect(answer).toEqual({ error: null, name: "Ana" });
expect(ana()).toEqual({ ...before, name: "Ana", newsletter: true });
const initial = { error: null, name: "" };
const save = (token, fields) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, () => updateProfile(initial, formData(fields)));
const ana = () => users.find((user) => user.id === "u_ana");
const ben = () => users.find((user) => user.id === "u_ben");
const before = { ...ana() };
await save("token-ben", { name: "Ben O.", userId: "u_ana" });
expect(ana()).toEqual(before);
expect(ben().name).toBe("Ben O.");
const initial = { error: null, name: "" };
const save = (token, fields) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, () => updateProfile(initial, formData(fields)));
const ana = () => users.find((user) => user.id === "u_ana");
const ben = () => users.find((user) => user.id === "u_ben");
const answer = await save("token-ben", { name: "Ben", newsletter: "on" });
expect(Object.keys(answer).sort()).toEqual(["error", "name"]);
expect(JSON.stringify(answer)).not.toMatch(/argon2|ben@example|storeCredit|role/);
const initial = { error: null, name: "" };
const save = (token, fields) => withRequest({ kind: "action", cookies: token ? { session: token } : {} }, () => updateProfile(initial, formData(fields)));
const ana = () => users.find((user) => user.id === "u_ana");
const ben = () => users.find((user) => user.id === "u_ben");
const before = JSON.stringify(users);
await expect(save(null, { name: "Mallory", role: "staff" })).rejects.toThrow("Sign in to change your profile.");
await expect(save("token-forged", { name: "Mallory" })).rejects.toThrow("Sign in to change your profile.");
expect(await save("token-ana", { name: " ", newsletter: "on" })).toEqual({ error: "Enter a name of up to 40 characters.", name: "" });
expect(await save("token-ana", { name: "x".repeat(41) })).toEqual({ error: "Enter a name of up to 40 characters.", name: "x".repeat(41) });
expect(JSON.stringify(users)).toBe(before);
expect(cache.revalidatedPaths).toEqual([]);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with A profile form that can't make you staff. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.