Access and roles

Your users must see their own data and never someone else's. You name the kinds of users in app.config.ts and write who may read and change which rows as Postgres row-level security policies. Postgres checks them on every statement, whether it comes from a page, an action, the API or SQL, and verify tries every role against every table before you ship. A table with no policy is closed.

When to use it

  • Members should see only their own bookings, orders or messages.
  • Staff should see everything; customers only what is theirs.
  • Someone should see only the records assigned to them, or their organisation's.
  • Signed-out visitors may browse a catalogue but nothing else.

1. Roles

// app.config.ts
import { defineApp } from "@appbricx/define";

export default defineApp({
  brand: { name: "Stillwater", tagline: "Yoga and pilates in Lisbon" },
  auth: { signup: { as: ["member"] }, admin: "instructor" },
  roles: {
    member: { kind: "consumer", label: "Member", profile: { table: "member_profile", create: true } },
    instructor: { kind: "staff", label: "Instructor" },
  },
});
  • kind: consumer (people who use the app: they can sign themselves up) or staff (people who run it: invited). It names a role; what the role may do is in the policies.
  • profile: the table holding one row per person with that role, linked by its user_id column. ctx.profile_id('member') is the signed-in member's row id there. With create: true the platform inserts the row at sign-up; see sign-in.
  • Every apply makes one demo sign-in per role; verify signs in with them.

2. Policies

One file per table (or per area) in db/access/. The booking app:

-- db/access/classes.sql: the timetable is public; instructors run it.
drop policy if exists class_session_public_read on class_session;
create policy class_session_public_read on class_session for select using (true);

drop policy if exists class_session_instructor_all on class_session;
create policy class_session_instructor_all on class_session for all
  using ((select ctx.has_role('instructor')));
-- db/access/booking.sql: members book and cancel their own mats; instructors see all.
drop policy if exists booking_member_read on booking;
create policy booking_member_read on booking for select
  using (member_id = (select ctx.profile_id('member')));

drop policy if exists booking_member_create on booking;
create policy booking_member_create on booking for insert
  with check (member_id = (select ctx.profile_id('member')) and status = 'booked');

drop policy if exists booking_member_cancel on booking;
create policy booking_member_cancel on booking for update
  using (member_id = (select ctx.profile_id('member')))
  with check (member_id = (select ctx.profile_id('member')) and status = 'cancelled');

drop policy if exists booking_instructor_all on booking;
create policy booking_instructor_all on booking for all
  using ((select ctx.has_role('instructor')));
  • using says which existing rows a role may read, change or delete; with check says what it may write. The cancel policy above lets a member change exactly one thing: their own booking, to cancelled.
  • Policies add up. A role gets a row when any of its policies allows it. No policy, no access.
  • Wrap the helpers in (select …) so Postgres works them out once per query instead of once per row.
  • drop policy if exists then create policy is the re-runnable form (Postgres has no create policy if not exists), and the only drop allowed in db/.
HelperAnswers
ctx.uid()The signed-in user's id, null for a visitor
ctx.role(), ctx.has_role('ops')The user's role; whether it is that role (never null)
ctx.profile_id('member')The user's row in that role's profile table, null otherwise
ctx.is_guest()Nobody is signed in

Signed-out visitors

A visitor has no user and no role. A policy whose using doesn't depend on them (using (true), using (status = 'published')) lets visitors read; a page they may open is then server-rendered with what they may read. Anything a visitor should do beyond reading goes through an action with roles: ["guest"].

Columns

Policies decide rows. To keep a column from a role, comment it: comment on column booking.email is '@pii @hide host'. The data API and server code leave @hide columns out for those roles (a comma list: @hide host, ops); @pii marks the column as personal data. For finer control, serve the role a view or an action instead of the table.

Code that must see past a policy

Sometimes a write must touch a row its writer can't: a member's booking moves the class's seat count. Put that in a security definer function or trigger. The lint asks for set search_path and a -- @definer <why> line directly above it: your sign-off that it checks who calls it and changes only what it should. Verify lists every such function. The booking app's seat trigger is one.

Members of the same organisation

In B2B apps rows belong to an organisation and only its members may see them. Write it the same way: a membership table, and policies that look through it.

-- db/access/org.sql
drop policy if exists membership_self on membership;
create policy membership_self on membership for select using (user_id = (select ctx.uid()));

drop policy if exists project_member_all on project;
create policy project_member_all on project for all
  using (exists (select 1 from membership m
                 where m.org_id = project.org_id and m.user_id = (select ctx.uid()) and m.status = 'active'))
  with check (exists (select 1 from membership m
                      where m.org_id = project.org_id and m.user_id = (select ctx.uid()) and m.status = 'active'));
  • The subquery reads membership under its own policies, so members must be able to read their own memberships (membership_self).
  • The with check stops a member creating a row in, or moving one to, an organisation they don't belong to.
  • For an admin-only action, add the membership's role to the condition (and m.role in ('owner', 'admin')).
  • A JSON app converted with appbricx migrate --to code gets an app_orgs() function for this, written for you.

Teams and invites

Staff are invited, not signed up. app_users { "action": "invite", "email", "name", "role" } makes the account and emails a link to choose a password; set_role, disable and enable manage it later. Inside the app, <TeamAdmin /> from @appbricx/ui gives the app's admin a roster page (add a person with a role, change a role, switch an account off). See who may sign up.

Check it

roles { "project_id": "…" }        // every role, its pages, and every table's policies as the database has them

explain { "project_id": "…", "about": "access", "table": "booking", "op": "update",
          "as": { "role": "member" }, "id": "…", "values": { "status": "attended" } }
// verdict, the layer that decided, each policy and whether it passes, a fix hint; always rolled back

query_data { "project_id": "…", "entity": "booking", "as": { "role": "member" } }    // what a member reads
sql { "project_id": "…", "sql": "select count(*) from booking", "as": { "role": "guest" } }
call_app { "project_id": "…", "path": "/__appbricx/api/v1/booking", "as": { "kind": "user", "role": "member" } }
verify { "project_id": "…", "checks": ["matrix"] }   // every role against every table, writes rolled back

Gotchas

  • Read the signed-out line in every verify report. It lists the tables visitors can read. If one should be private, its policy is too wide.
  • Don't call ctx.profile_id in the profile table's own policies. It reads that table, so it would recurse: use user_id = (select ctx.uid()) there.
  • Hiding a button is not access. The policies hold for every request, from a script as much as from your page.
  • Server code runs as its caller. An action is under the caller's policies; data-change and scheduled workflows run as the app and see every row, so keep their writes narrow.
  • Don't enable row-level security yourself: the platform enables and forces it on every table, and the lint refuses the statement.

Related