Write a change-password Server Action that signs the customer out on every other device
Leaf and Kettle keeps database sessions: the session cookie holds a token, and lib/sessions.ts keeps one row per signed-in browser. The account page's Change password form runs changePassword(previous, formData) through useActionState, with three fields: current, password, and confirm. Write the action in app/account/actions.ts.
Find who's asking from the session cookie with findSession(token). Without a cookie, or with one that names no session, redirect("/sign-in"). The person comes from the session, never from the form.
Then check, in this order, and return the first problem with done: false, changing nothing: checkPassword(userId, current) from @/lib/users must be true, or Your current password is wrong.; the new password must be at least 12 characters, or Use at least 12 characters.; and confirm must be the same, or The new passwords don't match. A missing field counts as empty.
When all is well, save it with setPassword, end every session the customer has with deleteUserSessions(userId), the one this browser is using included, start a new one with createSession(userId), and put its token in the session cookie: httpOnly, secure, sameSite: "lax", path: "/", and a week's maxAge, in seconds. Return { error: null, done: true }.
// cookie session=sess-1 (Ana's laptop); Ana also has sess-2 on her phone
// current "green-tea-42!", password and confirm "lapsang-by-the-fire"
// → passwords: u_ana is "lapsang-by-the-fire"; sess-1 and sess-2 are gone
// → cookie session=sess-3 (httpOnly, secure, sameSite "lax", path "/", maxAge 604800)
// → { error: null, done: true }
app/account/actions.ts"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { checkPassword, setPassword } from "@/lib/users";
import { createSession, deleteUserSessions, findSession } from "@/lib/sessions";
export type PasswordState = { error: string | null; done: boolean };
export async function changePassword(previous: PasswordState, formData: FormData): Promise<PasswordState> {
const token = (await cookies()).get("session")?.value;
const session = token ? await findSession(token) : null;
if (!session) redirect("/sign-in");
await setPassword(session.userId, String(formData.get("password") ?? ""));
return { error: null, done: true };
}
lib/users.ts (read-only)import "server-only";
// A stand-in for the users table. A real one keeps only a slow hash of each password
// (scrypt or argon2) and compares hashes; this one keeps the text to stay short.
export const passwords = new Map<string, string>([
["u_ana", "green-tea-42!"],
["u_ben", "oolong-at-noon"],
]);
/** Whether this is the user's password. */
export async function checkPassword(userId: string, password: string): Promise<boolean> {
return passwords.get(userId) === password;
}
/** Saves the user's new password. */
export async function setPassword(userId: string, password: string) {
passwords.set(userId, password);
}
lib/sessions.ts (read-only)import "server-only";
export type Session = { userId: string };
// A stand-in for the sessions table: one row for each browser someone is signed in on.
// A real token is long and random, like 32 bytes from crypto.getRandomValues.
export const sessions = new Map<string, Session>();
let made = 0;
/** Starts a session for the user and returns its token, for the session cookie. */
export async function createSession(userId: string): Promise<string> {
made += 1;
const token = `sess-${made}`;
sessions.set(token, { userId });
return token;
}
/** The session with this token, or null when there's none. */
export async function findSession(token: string): Promise<Session | null> {
return sessions.get(token) ?? null;
}
/** Ends every session the user has, on every device. */
export async function deleteUserSessions(userId: string) {
for (const [token, session] of sessions) {
if (session.userId === userId) sessions.delete(token);
}
}
- saves the new password, ends every session the customer had, and gives this browser a new one
- sends a visitor without a live session to sign in, and changes nothing
- refuses a wrong or missing current password, and keeps every session
- asks for at least 12 characters, typed the same twice
- changes only the signed-in customer's password, whatever the form says
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…