Users still see all tasks.
Likely cause: The page query remains find({}) even though writes were protected.
Check and correct: Filter the read on the server with the current session user ID.
PROJECT 5 · LESSON 15 OF 18
Enforce ownership in reads and all three mutations.
Continue from lesson 14: Build the account screens. Keep existing files; create or replace the complete files listed below.
Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.
A login screen is not enough to make data private. The server must constrain every read and every write to the current user. This lesson adds ownership at the database boundary so manipulating a URL or hidden input cannot cross that boundary.
Authentication tells you who is signed in. Authorization decides which task that person may read or change. A hidden form field can be edited, so ownership must be part of the database filter.
requireUser runs before each mutation. The user ID is derived from the verified session; the form supplies only task content and the target task ID.
Existing tasks from Project 4 have no owner and become invisible. Leave those learning records alone or remove them manually from your disposable lab database. Never automatically assign unowned records to whoever signs in first.
New tasks now store userId from requireUser. The create action does not accept userId from FormData. That prevents a caller from assigning a task to another person by submitting an extra field. createdAt and completed are still determined by the server-side create operation.
Project 4 tasks have no owner and will not match any userId filter. We leave them invisible rather than guessing who should own them. A real migration would need an explicit data policy; “give all old rows to the first person who logs in” would expose shared records arbitrarily.
The list changes from find({}) to find({ userId: user.id }). This prevents another user’s tasks from entering the rendered page at all. Filtering them with JavaScript in the browser would already have disclosed the records before hiding them.
Updates and deletes use both _id and userId in one database filter. Those conditions are combined: the record must have the requested ID and belong to the verified caller. This is stronger than merely checking that somebody is signed in.
Each action calls requireUser independently. The visible page may have been loaded earlier, a session may have ended, and requests can invoke the action without using the current UI. The mutation therefore checks its own caller at execution time.
When B submits A’s ID, the combined filter matches nothing. The action returns the same unavailable-task outcome as a missing record. It should not respond with A’s title or owner details just to explain why access failed.
An atomic filter on the write also avoids separating “check ownership” and “perform update” into unrelated operations. The database applies the requested change only to a document meeting both conditions when that write executes.
This still does not solve every concurrency problem: two tabs belonging to the same user may overwrite each other’s valid edits. Ownership and optimistic concurrency address different requirements.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The request session identifies user B.
requireUser supplies B’s trusted ID to the query.
The database looks for the requested task ID together with userId=B.
A’s task fails that combined filter, so it is neither returned nor changed.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
This module owns the task mutations and their server-side validation.
"use server";
import { requireUser } from "@/lib/session";
import { ObjectId } from "mongodb";
import { revalidatePath } from "next/cache";
import { tasks } from "@/lib/tasks";
export type Result = { message: string };
export async function createTask(
_previous: Result,
data: FormData,
): Promise<Result> {
const user = await requireUser();
const title = String(data.get("title") ?? "").trim();
if (!title || title.length > 120)
return { message: "Enter a title between 1 and 120 characters." };
try {
await tasks.insertOne({
title,
completed: false,
createdAt: new Date(),
userId: user.id,
});
} catch {
return { message: "Could not save. Please try again." };
}
revalidatePath("/");
return { message: "Task added." };
}
export async function updateTask(
_previous: Result,
data: FormData,
): Promise<Result> {
const user = await requireUser();
const id = String(data.get("id") ?? "");
const title = String(data.get("title") ?? "").trim();
if (!/^[a-f0-9]{24}$/i.test(id) || !title || title.length > 120)
return { message: "Check the task ID and title." };
try {
const result = await tasks.updateOne(
{ _id: new ObjectId(id), userId: user.id },
{ $set: { title, completed: data.get("completed") === "on" } },
);
if (!result.matchedCount) return { message: "Task no longer exists." };
} catch {
return { message: "Could not update task." };
}
revalidatePath("/");
return { message: "Task updated." };
}
export async function deleteTask(
_previous: Result,
data: FormData,
): Promise<Result> {
const user = await requireUser();
const id = String(data.get("id") ?? "");
if (!/^[a-f0-9]{24}$/i.test(id)) return { message: "Invalid task ID." };
try {
const result = await tasks.deleteOne({
_id: new ObjectId(id),
userId: user.id,
});
if (!result.deletedCount) return { message: "Task no longer exists." };
} catch {
return { message: "Could not delete task." };
}
revalidatePath("/");
return { message: "Task deleted." };
}
This Server Component reads the task list and composes the appropriate task controls.
import { requireUser } from "@/lib/session";
import { tasks } from "@/lib/tasks";
import NewTask from "@/components/new-task";
import TaskEditor from "@/components/task-editor";
export const dynamic = "force-dynamic";
export default async function TasksPage() {
const user = await requireUser();
const rows = await tasks
.find({ userId: user.id })
.sort({ createdAt: -1 })
.limit(100)
.toArray();
return (
<>
<h1>{user.name}’s tasks</h1>
<NewTask />
{rows.map((task) => (
<TaskEditor
key={task._id.toString() + task.title + task.completed}
task={{
id: task._id.toString(),
title: task.title,
completed: task.completed,
}}
/>
))}
{!rows.length && <p>No tasks yet.</p>}
</>
);
}
Using two isolated browser sessions, attempt to edit A’s task through B’s form by substituting its hidden ID.
B gets an unavailable-task message and A’s stored record is unchanged.
This tests the server rule directly. Merely checking that A’s task is absent from B’s screen would not verify the write protection.
Hiding edit buttons or checking only a layout is insufficient. Every read and mutation must enforce ownership.
Likely cause: The page query remains find({}) even though writes were protected.
Check and correct: Filter the read on the server with the current session user ID.
Likely cause: Those shared lab records do not contain userId.
Check and correct: Create new owned tasks to verify the flow. Do not automatically attach unowned records to the current user.
Add a due date while preserving the ownership filter in every operation.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
It is caller-controlled form input. It identifies what the caller wants to change but does not establish a right to change it.
The action needs a verified owner and must reject signed-out creation. Protecting only the list page would leave the write boundary incomplete.