Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 31 ยท Practice and Review

Practice Exercises with Solutions

Twelve hands-on exercises on security rules, RLS policies, queries, data modeling and auth tokens, each with a runnable stand-in solution you can edit.

Reading about rules and policies is one thing; writing them is another. This lesson gives you twelve exercises in four groups: security rules and policies, queries, data modeling, and auth tokens. Each exercise has a short task and then a runnable stand-in solution. The real Firebase and Supabase code needs an account and cannot run on this site, so the stand-ins are small JavaScript, Node or Python programs that capture the same logic. Where it helps, the real syntax is shown read-only next to it.

Try each exercise on your own first: edit the starter, press Run, and only then compare. Every stand-in is ours; it behaves like the real platform in the ways described, and nothing more.

Twelve exercises, four groups

Rules Exercises 1 to 3.
Queries Exercises 4 to 6.
Modeling Exercises 7 to 9.
Tokens Exercises 10 to 12.

Do them in order or jump to the group you need.

1 / 2

Group 1: Rules and policies

You should know Firestore Security Rules and Row Level Security Policies.

Exercise 1. Notes belong to a user. Only the owner may read, update or delete a note. Anyone signed in may create a note, but only with their own id as the owner.

Exercise 2. A comments table: everyone may read comments on published posts; only the comment author may delete their comment; an admin may delete any.

Exercise 3. Prevent privilege escalation: a user may update their own profile name, but never their own role field.

The real solution to exercise 1 in both products looks like this (read-only):

Text
// read-only: Firestore
match /notes/{id} {
  allow read, update, delete: if request.auth != null && resource.data.ownerId == request.auth.uid;
  allow create: if request.auth != null && request.resource.data.ownerId == request.auth.uid;
}
SQL
-- read-only: Supabase
create policy "owner reads" on notes for select using ((select auth.uid()) = owner_id);
create policy "owner updates" on notes for update
  using ((select auth.uid()) = owner_id) with check ((select auth.uid()) = owner_id);
create policy "owner deletes" on notes for delete using ((select auth.uid()) = owner_id);
create policy "create own" on notes for insert to authenticated
  with check ((select auth.uid()) = owner_id);

The stand-in solves all three with plain functions returning true or false:

JS Solutions 1 to 3: rule functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 3 is the same idea as with check in SQL and request.resource.data.role == resource.data.role in Firestore rules: always compare the new state with the old one.

Group 2: Queries

Background: Queries, Indexes and Pagination and Querying with supabase-js.

Exercise 4. From a list of products, find those in the category books that cost less than 20, sorted by price ascending, newest first on ties.

Exercise 5. Return page two of the same result with a page size of two, using a cursor (the last item of page one) instead of an offset.

Exercise 6. Firestore has no join. Given orders that store only customerId, show how storing the customer name inside each order (denormalization) lets you list orders with one query.

The real code (read-only):

JavaScript
// read-only: Firestore, exercises 4 and 5
const first = query(collection(db, "products"),
  where("category", "==", "books"), where("price", "<", 20),
  orderBy("price"), orderBy("createdAt", "desc"), limit(2));
// next page: startAfter(lastDoc)

// read-only: supabase-js, exercise 4
const { data } = await supabase.from("products").select("*")
  .eq("category", "books").lt("price", 20)
  .order("price").order("created_at", { ascending: false }).limit(2);
JS Solutions 4 to 6: filter, sort, cursor, denormalize

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A cursor stays correct when new rows arrive between page loads, while an offset can repeat or skip rows. The cost of denormalization is that renaming a customer must update every copy.

Group 3: Modeling

Background: Modeling Data: Documents vs Tables.

Exercise 7. Model a blog with authors and posts as tables (with a foreign key) and as nested documents. Count the reads needed to show a post with its author name in each model.

Exercise 8. Model "likes": a counter on the post plus a record of who liked it. Make liking twice by the same user count only once.

Exercise 9. Model a many-to-many relation (students and courses) and answer both "which courses has this student?" and "which students are in this course?".

Python Solutions 7 to 9: modeling in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Firestore the like record would be a document at posts/{postId}/likes/{uid} (the id makes it unique) and the counter would be updated with increment(1) in a transaction or batch. In Postgres a table likes(post_id, user_id, primary key (post_id, user_id)) gives uniqueness for free and count(*) replaces the counter.

Group 4: Tokens and claims

Background: OAuth Providers, Magic Links and JWTs and Users, Roles and Custom Claims.

Exercise 10. Decode a JWT payload without any library and print its expiry as a readable date.

Exercise 11. Decide whether a token is still valid at a given time, allowing 30 seconds of clock skew.

Exercise 12. Given decoded claims, allow an admin-only action only when app_metadata.role is admin, ignoring user_metadata.role.

The demo token below is made inside the program with node:crypto; it is a demo and has no relation to a real project.

Node.js Solutions 10 to 12: decode, expire, authorize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Decoding is not verifying. Anyone can read a payload; only checking the signature with the right key proves it was not changed. Real clients should let the SDK or the server verify tokens.

Stretch goals

  • Add a with check equivalent to exercise 2 so a comment cannot be re-assigned to another author.
  • Extend exercise 5 so the cursor includes both price and id, which stays stable when prices tie.
  • Write a stand-in that denies a token whose iss (issuer) does not match your project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why compare the new document with the old one when users edit profiles?

    Validating only the new value misses fields the user was not supposed to change; comparing old and new catches them.
  2. 2. What is the benefit of cursor pagination over offsets?

    A cursor continues after a known row, so inserts do not shift the page.
  3. 3. A JWT payload can be decoded by anyone. What proves it is genuine?

    Encoding is not encryption; the signature is what prevents tampering.
  4. 4. Which metadata may decide whether someone is an admin?

    Users can modify user_metadata themselves, so only server-controlled data is trustworthy.

Summary

  • Rules and policies compare who is asking with the row, and compare old with new on updates.
  • Cursors give stable pages; denormalization trades extra writes for fewer reads.
  • A document or table model should follow the questions the app asks.
  • Decoding a token reveals claims; verifying its signature and expiry makes them trustworthy.
  • Trust only server-controlled data for roles.

Next: Interview Questions