Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 31 ยท Real-World Projects

Project: Blog with Auth, Storage and Roles

Build a blog backend with editor and admin roles, image uploads and a publish workflow, in both Firebase and Supabase, with a runnable permission engine.

A blog looks simple until more than one person writes for it. Readers should see only published posts. Authors should edit their own drafts. Editors publish. Admins manage people. And every post may have a cover image that must be uploaded, validated and shown. Together that is a small but realistic content management system (CMS), and it touches almost everything from this track: authentication, roles and claims, security rules, Row Level Security and file storage.

In this project you design the rules once, then see them twice: as read-only Firebase code and as read-only Supabase SQL. Neither can run on this site, because both need a project and an account. To make the logic testable, you also get runnable stand-ins: a permission engine and a publishing state machine written in plain JavaScript. The stand-ins are ours; the real platforms enforce the same decisions inside their own servers.

What the blog must do

Readers See published posts only.
Authors Write and edit their own drafts.
Editors Review and publish any post.
Admins Change roles and delete anything.

Four roles, one table of posts, one bucket of images.

1 / 2

Step 1: Model the data

Each post needs an id, an author, a title, a body, a cover image path and a status. Each person needs a role. Keep the role somewhere users cannot edit it, as explained in Users, Roles and Custom Claims.

In Firebase, put the role in a custom claim (set from a trusted server, such as a Cloud Function) and the posts in a posts collection:

JavaScript
// read-only: Firebase data shape
// posts/{postId}
{
  authorId: "uid-ana",
  title: "Hello world",
  body: "โ€ฆ",
  coverPath: "covers/uid-ana/hello.webp",
  status: "draft",            // draft | review | published
  updatedAt: serverTimestamp()
}
// claims on the ID token: { role: "author" | "editor" | "admin" }

In Supabase, use a profile table plus a posts table. The role lives in profiles, which only admins and the server can write:

SQL
-- read-only: Supabase schema
create type public.app_role as enum ('author', 'editor', 'admin');
create type public.post_status as enum ('draft', 'review', 'published');

create table public.profiles (
  id uuid primary key references auth.users (id) on delete cascade,
  display_name text not null,
  role public.app_role not null default 'author'
);

create table public.posts (
  id bigint generated always as identity primary key,
  author_id uuid not null references public.profiles (id) default auth.uid(),
  title text not null check (char_length(title) between 3 and 120),
  body text not null,
  cover_path text,
  status public.post_status not null default 'draft',
  updated_at timestamptz not null default now()
);

alter table public.profiles enable row level security;
alter table public.posts enable row level security;

Step 2: The rules, in words first

Write the permission table before any code. It is your specification, and later it becomes your test list.

Action Reader / guest Author Editor Admin
Read published post yes yes yes yes
Read a draft or in-review post no own only yes yes
Create post (as draft) no yes yes yes
Edit post no own, unpublished any any
Submit for review no own own any
Publish no no yes yes
Delete post no own draft no yes
Change roles no no no yes

Two details deserve attention. First, an author cannot edit a post once it is published; they ask an editor, which keeps the public version stable. Second, "create" must force status to draft, otherwise an author could create a post that is already published and skip the workflow.

Step 3: Firebase rules (read-only)

Text
// read-only: Firestore rules (sketch)
rules_version = '2';
service cloud.firestore {
  match /databases/{db}/documents {
    function role() { return request.auth.token.role; }
    function signedIn() { return request.auth != null; }
    function isStaff() { return signedIn() && (role() == 'editor' || role() == 'admin'); }

    match /posts/{postId} {
      allow get: if resource.data.status == 'published'
                 || (signedIn() && resource.data.authorId == request.auth.uid)
                 || isStaff();

      allow create: if signedIn()
                    && request.resource.data.authorId == request.auth.uid
                    && request.resource.data.status == 'draft';

      allow update: if isStaff()
                    || (signedIn()
                        && resource.data.authorId == request.auth.uid
                        && resource.data.status != 'published'
                        && request.resource.data.status in ['draft', 'review']
                        && request.resource.data.authorId == resource.data.authorId);

      allow delete: if (signedIn() && role() == 'admin')
                    || (signedIn() && resource.data.authorId == request.auth.uid
                        && resource.data.status == 'draft');
    }
  }
}

Remember that Firestore rules are not filters. A list query for the public page must itself contain where("status", "==", "published"), otherwise the whole query is rejected, because the rule cannot be proven for every document. The page that lists a person's drafts adds a where("authorId", "==", uid) filter in the same way.

Step 4: Supabase policies (read-only)

SQL
-- read-only: helper that reads the caller's role
create function public.current_role() returns public.app_role
language sql stable security definer set search_path = ''
as $$ select role from public.profiles where id = (select auth.uid()) $$;

create policy "read published, own, or staff"
  on public.posts for select
  using (
    status = 'published'
    or author_id = (select auth.uid())
    or (select public.current_role()) in ('editor', 'admin')
  );

create policy "create own drafts"
  on public.posts for insert to authenticated
  with check (author_id = (select auth.uid()) and status = 'draft');

create policy "edit own unpublished or staff edit any"
  on public.posts for update to authenticated
  using (
    (select public.current_role()) in ('editor', 'admin')
    or (author_id = (select auth.uid()) and status <> 'published')
  )
  with check (
    (select public.current_role()) in ('editor', 'admin')
    or (author_id = (select auth.uid()) and status in ('draft', 'review'))
  );

create policy "delete own drafts or admin"
  on public.posts for delete to authenticated
  using (
    (select public.current_role()) = 'admin'
    or (author_id = (select auth.uid()) and status = 'draft')
  );

The using and with check pair on update does the same job as the Firebase resource versus request.resource comparison. Because the helper function is security definer, it lives best in a private schema in a real project, as warned in Security Pitfalls in Both Platforms.

Step 5: Image uploads

Cover images go to a bucket. The path convention covers/<user id>/<file> makes ownership checkable from the path alone. The client uploads with the SDK, then saves the path in the post.

JavaScript
// read-only: Firebase Storage
const storageRef = ref(storage, `covers/${user.uid}/${file.name}`);
await uploadBytes(storageRef, file, { contentType: file.type });

// read-only: Supabase Storage
await supabase.storage
  .from("covers")
  .upload(`${user.id}/${file.name}`, file, { contentType: file.type, upsert: false });

Both platforms need access rules on the bucket (only the owner writes into their own folder; reads are public or signed) and checks on size and type. Details are in File Storage and Uploads.

The stand-in permission engine

The table from step 2 becomes data. The function can(user, action, post) is a pure function with no network, so you can test every cell. This is the very idea to keep in a real project: one decision function, many tests.

JS Stand-in permission engine for the blog

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

No output.

Read the two tables slowly. bo is an author, yet cannot read ana's draft. ana can no longer edit once the post is published, but the editor can. Every row corresponds to a rule you wrote in both Firebase and SQL.

The publishing workflow

Permissions say who may act. A state machine says which moves are legal. A post may go draft to review, review back to draft, review to published, and published back to draft (an unpublish). It may never jump from draft straight to published. The stand-in below combines both checks, exactly like a trusted server function would.

Node.js Stand-in workflow: permissions plus legal transitions

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.

In a real project this logic lives in one place the client cannot skip: a Cloud Function or Supabase RPC/Edge Function for the transitions, plus rules or policies as the second lock. Rules alone can check "status may only become published if the caller is an editor," but they cannot easily verify the previous-to-next pair for every case, so many teams keep a server function for publishing and forbid clients from writing status = 'published' directly.

Hardening checklist

  • Never trust a role sent by the browser; read it from a claim or a table only admins write.
  • Force status to draft on create and block changing authorId or author_id on update.
  • Validate titles and body lengths with check constraints or rules, and file type and size in storage.
  • Delete a post's cover image when you delete the post (a function trigger can do it).
  • Write a test for every cell in the permission table, as a guest, an author, an editor and an admin.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must the create rule force status to 'draft'?

    Without the check, the workflow could be bypassed on insert.
  2. 2. Where should a user's role be stored?

    Anything the user can change cannot decide access.
  3. 3. A public page lists posts in Firestore. What must the query contain?

    Firestore rules are not filters: a query that could return forbidden documents is rejected.
  4. 4. What does the state machine add on top of the permission table?

    Permissions answer who may act; transitions answer which moves are allowed from the current state.

Summary

  • Write the role-by-action table first; it drives rules, policies and tests.
  • Store roles in claims or a protected table, never in user-editable data.
  • Firestore rules compare resource and request.resource; Supabase uses using and with check.
  • Uploads go to owner-scoped paths with size and type checks.
  • Add a state machine and keep publishing in trusted server code.

Next: Project: SaaS Starter with Teams