Command Palette

Search for a command to run...

Hectal
Phase 21: Security in React Apps
React · Exercise 5 of 5 Previous
Advanced

Lock down a server function

saveNote stands in for a "use server" function: the form calls it through useActionState, but anyone could call it with any fields. The form uses noValidate and lets you edit the note id, so you can play the attacker. Right now it saves anything to any note and returns the whole note record.

Make saveNote do the four steps: (1) get the session with getSession(); (2) validate: noteId and text must be strings, and text trimmed must be 1 to 200 characters, otherwise return { error: "Please write 1 to 200 characters." }; (3) authorise: if the note doesn't exist or its ownerId isn't the session's userId, return { error: "Not found." }; (4) on success save the trimmed text and return exactly { ok: true }.

The UI already shows state.error (or Saved.) in #status and the raw returned object in #result.

What Check tests

  1. Blank text is rejected
  2. Text over 200 characters is rejected
  3. Someone else's note can't be changed
  4. A note that doesn't exist gives Not found.
  5. Your own note saves the trimmed text
  6. Success returns exactly { ok: true }

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.