Module 06 · Lesson 6.3
Roles and Permissions
On this page
- What you will learn
- Roles and the permission table
- Linking sign-in to a role: migration 004
- One function for permissions, plus ownership checks
- Table-driven tests for permissions
- Step-by-step workflow
- Working with an assistant on roles
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A clinic has many keys. The front-desk team holds the diary. The physiotherapists see their own day. The practice manager can change almost anything. A patient holds one key, to their own appointments. The people were already on your stakeholder table in Module 1.
In this lesson you turn that table into rules the server can enforce. You write a permission table, link each signed-in email to a role with a database migration, and put every decision in one function. Then you test the whole table, so a change to a permission cannot slip in unnoticed.
What you will learn
- Turn roles from a stakeholder table into a permission table that the business owner can review.
- Link a signed-in identity to a role and a patient or clinician record with a database migration.
- Enforce permissions in one place, with deny by default and ownership checks.
- Write table-driven tests that check every role against every action.
Before you start
- Completed Sessions and Password Handling, or know how a session and sign-in work.
- Your stakeholder table from Stakeholders and Workflows, or the Tidewell roles in this lesson.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
Roles and the permission table
- Role
- A job-shaped label that carries a set of permissions. A person has one role in Tidewell, such as patient or front desk.
- Permission
- Permission to do one named action, such as "view booking history". Permissions attach to actions, not to screens.
- Scope
- How far a permission reaches. Tidewell uses three: any (all records), own (only the person's own) and none.
- Deny by default
- If the rules say nothing, the answer is no. A forgotten row never opens a door.
- Least privilege
- Give each role only what its job needs. A physiotherapist needs their own day, not the whole diary.
Tidewell's roles come from the stakeholder table in Module 1. The four that use the system are patient, front-desk staff, physiotherapist and practice manager. The clinic owner decides about data and hosting, but does not use the booking system day to day.
So the owner has no role in the table. Confirm that with the owner.
Here is the permission table. It is a business document first and code second. Each row is an action that some requirement needs.
FR-02 gives the patient rows, FR-04 gives front desk its rows and FR-05 gives the history row. FR-03 and CON-01 give the approval rows that you meet in a later lesson.
| Action | Patient | Front desk | Physiotherapist | Practice manager |
|---|---|---|---|---|
| View free slots | yes | yes | yes | yes |
| Book, move or cancel own booking (at least 24 hours ahead) | yes | – | – | – |
| Book, move or cancel any booking, including inside 24 hours (FR-04) | no | yes | no | yes |
| View the day's appointments | no | all | own only | all |
| Create slots from a working pattern | no | yes | no | yes |
| View booking change history (FR-05) | no | yes | no | yes |
| Approve a waiting-list offer (FR-03) | no | yes | no | yes |
| Request a clinician's day cancellation | no | yes | yes (own day) | yes |
| Approve a clinician's day cancellation | no | no | no | yes |
| Request deletion of a patient record | no | yes | no | yes |
| Approve deletion of a patient record | no | no | no | yes |
| Manage staff accounts | no | no | no | yes |
- Own versus any. A patient manages only their own bookings. Front desk and the practice manager manage any booking, even inside the 24-hour notice period. That is a different row, because it is a different power.
- Request versus approve. Some actions are split into two steps. Different roles hold each step, so one person cannot do both alone.
- The physiotherapist is narrow on purpose. They see their own day and may ask for their own day to be cancelled. Nothing more.
Linking sign-in to a role: migration 004
The sign-in library knows that a person proved ownership of an email address. It does not know that this person is Tidewell's front-desk team.
Tidewell keeps its own small table for that. The library's tables stay untouched, so a library upgrade never damages your roles.
-- Links a signed-in identity (an email the sign-in library has confirmed) to a Tidewell role.
CREATE TABLE app_users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
role text NOT NULL CHECK (role IN ('patient', 'front_desk', 'physiotherapist', 'practice_manager')),
patient_id bigint REFERENCES patients (id),
clinician_id bigint REFERENCES clinicians (id),
active boolean NOT NULL DEFAULT true,
CONSTRAINT patient_role_has_patient CHECK ((role = 'patient') = (patient_id IS NOT NULL))
);What each part does
emailis unique, so one email means one account. Store it in lower case.roleis limited by aCHECKrule to the four known roles. A typo cannot create a fifth.patient_idlinks a patient to their patient record.clinician_idlinks a physiotherapist to their clinician record.activelets the practice manager switch an account off, without deleting its history. The code reads it on every request.- The last rule says: a patient has a patient record, and nobody else does.
(role = 'patient') = (patient_id IS NOT NULL)means both sides must be true together, or both false.
In your project, npm run migrate applies the new file. Here is the migration running in PGlite, a real PostgreSQL engine inside Node, together with six attempts to add accounts.
The first two are fine. The rest break a rule on purpose.
async function attempt(label: string, sql: string) {
try {
await db.exec(sql);
console.log(`${label}: accepted`);
} catch (error) {
console.log(`${label}: refused - ${(error as Error).message}`);
}
}applied: 001_core_tables.sql, 002_bookings_and_changes.sql, 003_waiting_list.sql, 004_app_users.sql, 005_email_outbox.sql, 006_approvals.sql
1. patient linked to a patient record: accepted
2. front desk with no record: accepted
3. patient with no patient record: refused - new row for relation "app_users" violates check constraint "patient_role_has_patient"
4. front desk linked to a patient record: refused - new row for relation "app_users" violates check constraint "patient_role_has_patient"
5. a role that does not exist: refused - new row for relation "app_users" violates check constraint "app_users_role_check"
6. the same email twice: refused - duplicate key value violates unique constraint "app_users_email_key"Attempts 3 and 4 show the last rule at work. A patient without a record is refused, and so is a front-desk account linked to a patient record. Attempt 5 hits the role list, and attempt 6 hits the unique email.
The first line also shows that migrations 005 and 006 exist. You meet them in the next two lessons.
From a confirmed email to a session
Now the code that joins the two. The library hands over the confirmed email, and Tidewell looks it up.
Nothing found, or an account switched off, means no session. This is where getSession from the first lesson gets its answer.
interface UserRow {
user_id: number;
role: Role;
patient_id: number | null;
clinician_id: number | null;
}
// The link between a confirmed email and a Tidewell role (table app_users, migration 004).
export async function loadSessionForEmail(db: Db, email: string): Promise<Session | null> {
const { rows } = await db.query<UserRow>(
`SELECT id::int AS user_id, role, patient_id::int AS patient_id, clinician_id::int AS clinician_id
FROM app_users WHERE email = $1 AND active`,
[email.trim().toLowerCase()],
);
if (rows.length === 0) return null;
const row = rows[0];
return {
userId: row.user_id,
role: row.role,
...(row.patient_id !== null ? { patientId: row.patient_id } : {}),
...(row.clinician_id !== null ? { clinicianId: row.clinician_id } : {}),
};
}
// Where the library plugs in: it says which email is signed in, and Tidewell adds the role.
export function createGetSession(
db: Db,
identityFromRequest: (request: Request) => Promise<{ email: string } | null>,
): GetSession {
return async (request) => {
const identity = await identityFromRequest(request);
return identity === null ? null : loadSessionForEmail(db, identity.email);
};
}loadSessionForEmailreads the user row for an email that is still active. It cleans the email first, with trim and lower case.- The id columns are cast with
::int, as in Module 4, because node-postgres returns big numbers as text. createGetSessionis the seam. The library suppliesidentityFromRequest, which returns the signed-in email ornull. Tidewell does the rest.
One function for permissions, plus ownership checks
Permissions go in one place, as data. A reviewer can read the table in one glance. And a change to a permission is one change, not a hunt through twenty handlers for if (role === ...).
// src/lib/permissions.ts: the one place that says who may do what.
import { notAllowed } from "./problem";
import type { Session } from "./session";
export const ROLES = ["patient", "front_desk", "physiotherapist", "practice_manager"] as const;
export type Role = (typeof ROLES)[number];
// "any": no limit on whose data. "own": only their own. "none": not allowed.
export type Scope = "any" | "own" | "none";
export const PERMISSIONS = {
view_free_slots: { patient: "any", front_desk: "any", physiotherapist: "any", practice_manager: "any" },
manage_own_booking: { patient: "own", front_desk: "none", physiotherapist: "none", practice_manager: "none" },
manage_any_booking: { patient: "none", front_desk: "any", physiotherapist: "none", practice_manager: "any" },
view_day_appointments: { patient: "none", front_desk: "any", physiotherapist: "own", practice_manager: "any" },
create_slots: { patient: "none", front_desk: "any", physiotherapist: "none", practice_manager: "any" },
view_booking_history: { patient: "none", front_desk: "any", physiotherapist: "none", practice_manager: "any" },
approve_waitlist_offer: { patient: "none", front_desk: "any", physiotherapist: "none", practice_manager: "any" },
request_day_cancellation: { patient: "none", front_desk: "any", physiotherapist: "own", practice_manager: "any" },
approve_day_cancellation: { patient: "none", front_desk: "none", physiotherapist: "none", practice_manager: "any" },
request_patient_deletion: { patient: "none", front_desk: "any", physiotherapist: "none", practice_manager: "any" },
approve_patient_deletion: { patient: "none", front_desk: "none", physiotherapist: "none", practice_manager: "any" },
manage_staff_accounts: { patient: "none", front_desk: "none", physiotherapist: "none", practice_manager: "any" },
} as const satisfies Record<string, Record<Role, Scope>>;
export type Action = keyof typeof PERMISSIONS;as constfreezes the values as exact words.satisfiesmakes TypeScript check that every row names all four roles, with a valid scope.Actionis built from the row names. A typo such as"view_booking_histroy"is a compile error, not a silent denial.- Each name matches a row in the table above. For example,
manage_own_bookingis the second row andview_day_appointmentsis the fourth.
// Deny by default: an unknown role or action gets "none", never "any".
export function scopeOf(role: string, action: Action): Scope {
if (!Object.hasOwn(PERMISSIONS, action)) return "none";
const row: Record<string, Scope> = PERMISSIONS[action];
return Object.hasOwn(row, role) ? row[role] : "none";
}
export function can(role: string, action: Action): boolean {
return scopeOf(role, action) !== "none";
}
// For handlers: throws 403 when the role may not do this at all, otherwise returns the scope.
export function requirePermission(session: Session, action: Action): Scope {
const scope = scopeOf(session.role, action);
if (scope === "none") throw notAllowed();
return scope;
}
// Ownership check for actions that concern one clinician's day: "own" means their own day only.
export function requirePermissionForClinician(session: Session, action: Action, clinicianId: number): void {
const scope = requirePermission(session, action);
if (scope === "own" && session.clinicianId !== clinicianId) throw notAllowed();
}What each part does
scopeOfreturns any, own or none. It starts with a refusal: an unknown action or an unknown role gives "none".Object.hasOwnmatters. Without it, a made-up action such as"toString"would find a built-in JavaScript property and might not be refused.canis the yes-or-no version. Use it for the interface too, for example to hide a button. The server still checks every request.requirePermissionis for handlers. It throws the 403 problem when the scope is none, and otherwise returns the scope so the handler can apply it.requirePermissionForClinicianadds an ownership check for one clinician's day. "Own" means only if the session's clinician is that clinician.
Two kinds of ownership
| Kind | Example | How it is enforced |
|---|---|---|
| A person's own records | A patient cancels a booking. | The patient id comes from the session and sits in the SQL: WHERE id = $1 AND patient_id = $2. Other people's records answer 404. |
| One clinician's day | A physiotherapist asks to cancel their day. | requirePermissionForClinician compares the session's clinician with the day's clinician. A different clinician answers 403. |
| A scope that shapes the query | "View the day's appointments": all for front desk, own only for a physiotherapist. | The handler reads the scope. For "own" it filters by the session's clinician. For "any" it adds no filter. |
Table-driven tests for permissions
A table-driven test keeps its cases in a table and runs one check for each row. It suits permissions well, because the permission table is already a table.
The test below does not read the code's table. It has its own copy, typed out separately.
That duplicate is deliberate. If the test only read the code's table, it would agree with the code whatever the code said. With two copies, a change must be made twice, and a reviewer sees it.
// The expected table is typed out here on purpose, apart from the code.
// A change to a permission must then be made in two places, which a reviewer will notice.
const ROLES: Role[] = ["patient", "front_desk", "physiotherapist", "practice_manager"];
const EXPECTED: Record<Action, Scope[]> = {
// patient front_desk physio manager
view_free_slots: ["any", "any", "any", "any"],
manage_own_booking: ["own", "none", "none", "none"],
manage_any_booking: ["none", "any", "none", "any"],
view_day_appointments: ["none", "any", "own", "any"],
create_slots: ["none", "any", "none", "any"],
view_booking_history: ["none", "any", "none", "any"],
approve_waitlist_offer: ["none", "any", "none", "any"],
request_day_cancellation: ["none", "any", "own", "any"],
approve_day_cancellation: ["none", "none", "none", "any"],
request_patient_deletion: ["none", "any", "none", "any"],
approve_patient_deletion: ["none", "none", "none", "any"],
manage_staff_accounts: ["none", "none", "none", "any"],
};
const isForbidden = (error: unknown) => error instanceof ApiError && error.problem.status === 403;
describe("permission table: one test per action", () => {
for (const [action, scopes] of Object.entries(EXPECTED) as [Action, Scope[]][]) {
it(action, () => {
ROLES.forEach((role, i) => assert.equal(scopeOf(role, action), scopes[i], `${role} / ${action}`));
});
}
});The runner is the one built into Node, node:test. Module 7 teaches it properly.
The loop creates one test for each action, and each test checks all four roles. Then come the tests for deny by default and for ownership.
describe("deny by default", () => {
it("an unknown role gets nothing", () => assert.equal(can("owner", "view_free_slots"), false));
it("an empty role gets nothing", () => assert.equal(can("", "manage_staff_accounts"), false));
it("an action that is not in the table gets nothing", () => {
assert.equal(can("practice_manager", "toString" as Action), false);
});
});
describe("ownership", () => {
const ownDay = { userId: 4, role: "physiotherapist", clinicianId: 1 } as const;
it("a physiotherapist may request cancelling their own day", () => {
assert.doesNotThrow(() => requirePermissionForClinician(ownDay, "request_day_cancellation", 1));
});
it("a physiotherapist may not request it for a colleague's day", () => {
assert.throws(() => requirePermissionForClinician(ownDay, "request_day_cancellation", 2), isForbidden);
});
it("front desk may request it for any clinician", () => {
assert.doesNotThrow(() => requirePermissionForClinician({ userId: 3, role: "front_desk" }, "request_day_cancellation", 2));
});
it("requirePermission throws 403 when the scope is none", () => {
assert.throws(() => requirePermission({ userId: 3, role: "front_desk" }, "approve_day_cancellation"), isForbidden);
});
});describe("from a confirmed email to a session", () => {
it("finds a patient and their patient record", async () => {
const db = await freshDatabase();
assert.deepEqual(await loadSessionForEmail(db, "Patient.A@example.com "), { userId: 1, role: "patient", patientId: 1 });
});
it("finds a physiotherapist and their clinician record", async () => {
const db = await freshDatabase();
assert.deepEqual(await loadSessionForEmail(db, "physio.a@example.com"), { userId: 4, role: "physiotherapist", clinicianId: 1 });
});
it("an email nobody registered gets no session", async () => {
const db = await freshDatabase();
assert.equal(await loadSessionForEmail(db, "stranger@example.com"), null);
});
it("a deactivated account gets no session", async () => {
const db = await freshDatabase();
await db.query("UPDATE app_users SET active = false WHERE email = $1", ["frontdesk.a@example.com"]);
const getSession = createGetSession(db, async () => ({ email: "frontdesk.a@example.com" }));
assert.equal(await getSession(new Request("http://localhost/")), null);
});These last four tests use PGlite and the real migration. They also cover the cases that must be refused: an unknown email, and an account that has been switched off.
▶ permission table: one test per action
✔ view_free_slots (0.5605ms)
✔ manage_own_booking (0.0676ms)
✔ manage_any_booking (0.1031ms)
✔ view_day_appointments (0.0476ms)
✔ create_slots (0.0362ms)
✔ view_booking_history (0.032ms)
✔ approve_waitlist_offer (0.0724ms)
✔ request_day_cancellation (0.0741ms)
✔ approve_day_cancellation (0.1436ms)
✔ request_patient_deletion (0.191ms)
✔ approve_patient_deletion (0.0424ms)
✔ manage_staff_accounts (0.0281ms)
✔ permission table: one test per action (2.1338ms)
▶ deny by default
✔ an unknown role gets nothing (0.0793ms)
✔ an empty role gets nothing (0.0401ms)
✔ an action that is not in the table gets nothing (0.0322ms)
✔ deny by default (0.2206ms)
▶ ownership
✔ a physiotherapist may request cancelling their own day (0.1523ms)
✔ a physiotherapist may not request it for a colleague's day (0.2891ms)
✔ front desk may request it for any clinician (0.0619ms)
✔ requirePermission throws 403 when the scope is none (0.0544ms)
✔ ownership (0.627ms)
▶ from a confirmed email to a session
✔ finds a patient and their patient record (1249.131ms)
✔ finds a physiotherapist and their clinician record (820.2677ms)
✔ an email nobody registered gets no session (1114.5485ms)
✔ a deactivated account gets no session (2131.7592ms)
✔ from a confirmed email to a session (5316.0764ms)
ℹ tests 23
ℹ suites 4
ℹ pass 23
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 15793.3809Now change one cell in the code, for example give front desk the approval for a day cancellation. The test for that action fails and names the role and the action. A permission can no longer widen by accident.
Step-by-step workflow
Step 1: Start from the stakeholder table
List the roles that will use the system. Leave out stakeholders who only decide or are affected, and say so.
What you should see: A list of roles, with the owner's confirmation.
Step 2: List the actions from the requirements
Go through each requirement and workflow step. Write the action it needs, one per row.
What you should see: Each row traces to a requirement ID.
Step 3: Fill in the table with any, own or none
For each role and action, decide the scope. Where you do not know, write "Decision needed" and the role who decides.
What you should see: A full table with no blank cells.
Step 4: Review it with the practice manager
Walk through the table in plain words. Ask what each role should never be able to do.
What you should see: A table the business owner has agreed to.
Step 5: Write the migration and the seed data
Add the table that links an email to a role. Use made-up accounts for tests.
What you should see: Migration 004 applies cleanly, and the rule against bad links holds.
Step 6: Put the table in code, and use it in every handler
Keep one table, one lookup and one
requirePermission. Add ownership checks where the scope is "own".What you should see: No handler compares a role name directly.
Step 7: Write the expected table in the test, from the document
Copy it from the agreed table, not from the code. Add tests for deny by default and ownership.
What you should see: A failing test whenever the code and the document disagree.
- Stakeholder table
Roles
- Actions
From requirements
- Permission table
any, own, none
- Owner review
Practice manager
- Code and migration
One place
- Table-driven test
Every cell
The business owner signs off the table. The tests keep the code faithful to it.
Working with an assistant on roles
| Task | Assistant's part | Your part |
|---|---|---|
| Draft the actions list | Reads your requirements and proposes action names. | Remove actions nothing asks for. Add the ones it missed. |
| Find gaps in the table | Spots actions with no row, or roles with odd combinations. | Decide each one with the practice manager. |
| Write the lookup code | Drafts the table and the functions from your document. | Check deny by default and that no handler compares roles directly. |
| Write the tests | Drafts a table-driven test. | Type the expected table from the document, not from the code. |
| Choose who may do what | Nothing. It guesses from typical systems. | Take the table to the people who own the rules. |
Conclusion and your next step
Roles come from your stakeholders, and permissions come from your requirements. Tidewell holds both in one table that the practice manager has reviewed. Migration 004 links a signed-in email to a role. One function enforces the table, and a table-driven test checks every cell.
Your next step: write the permission table for your capstone, with a trace to a requirement on every row. Mark every unknown cell as a decision. Then continue to Integrating an External Service, where Tidewell sends its first emails safely.
To turn requirements into checks, try the Test Case Design from Acceptance Criteria prompt. To compare your table with a similar clinic, see Appointment Booking Portal.
Reusable prompt
Permission table review
Asks the assistant to check a permission table against the requirements and find gaps, risky combinations and open decisions, without writing code or changing any rule.
You are reviewing a permission table. Do not write code. Do not change any permission. Do not invent roles.
Fictional clinic: Tidewell Physiotherapy. Roles: patient, front_desk, physiotherapist, practice_manager. The clinic owner is a stakeholder but has no role in the system.
Requirements that need actions:
FR-01 see free slots. FR-02 a patient moves or cancels their own booking. FR-03 cancelled slots are offered to the waiting list. FR-04 front desk create, move and cancel bookings for patients. FR-05 every change to a booking is recorded, and staff can see the history. CON-01 patient data is held under the clinic's data-protection duties.
Permission table (any = all records, own = only their own, none = not allowed):
{{paste the table, one row per action and one column per role}}
Tasks:
1. List requirements or workflow steps that have no row in the table.
2. List rows that no requirement needs. Say which requirement you looked at.
3. List risky combinations, such as one role able to request and approve the same thing.
4. Say which rows depend on an ownership rule, and what the rule is.
5. List every cell you are unsure about under "Decision needed", with the role who should decide.
6. Write one test line per decision, in the form: role, action, expected scope.Show the reusable template
Replace each {{placeholder}} with your own details.
You are reviewing a permission table. Do not write code. Do not change any permission. Do not invent roles.
Context: {{organisation_and_roles}}. Stakeholders with no role: {{stakeholders_without_a_role}}.
Requirements that need actions:
{{requirements}}
Permission table (any = all records, own = only their own, none = not allowed):
{{permission_table}}
Tasks:
1. List requirements or workflow steps that have no row in the table.
2. List rows that no requirement needs. Say which requirement you looked at.
3. List risky combinations, such as one role able to request and approve the same thing.
4. Say which rows depend on an ownership rule, and what the rule is.
5. List every cell you are unsure about under "Decision needed", with the role who should decide.
6. Write one test line per decision, in the form: role, action, expected scope.Expected output and limitations
Six short lists: missing rows, unneeded rows, risky combinations, ownership rules, a Decision needed list with roles, and one test line per decision. A good answer cites requirement IDs and changes no cell.
1. Missing rows
- FR-04 says front desk can create bookings for patients. The table has "book any booking" but no row for creating a patient record.
(Not in the requirements yet: raise it with the practice manager.)
3. Risky combinations
- Practice manager can request and approve patient deletion. Check the two-person rule.
4. Ownership rules
- "Book own booking": the patient id comes from the session.
- "Request day cancellation": a physiotherapist may only name their own clinician id.
5. Decision needed
- Should the physiotherapist see the names of patients on their own day? Role: practice manager.
- Should the clinic owner be able to sign in at all? Role: clinic owner.
6. Test lines
physiotherapist, view_day_appointments, own
practice_manager, approve_patient_deletion, anyLimitations to keep in mind
- The assistant only sees the table you pasted. It cannot tell whether the code matches it.
- It may suggest extra roles or rows. Anything no requirement asks for belongs under Decision needed.
- A review is a reading exercise. Only the table-driven test shows that the code enforces the table.
Common errors and how to fix them
Role checks are scattered through handlers as if (role === "front_desk").
Why it happens: Each handler was written on its own, with the quickest check.
Fix: Keep one permission table and one lookup. Handlers call requirePermission with an action name.
An unknown role or action is treated as allowed.
Why it happens: The lookup had no default, or used a plain object lookup that finds inherited names.
Fix: Start from a refusal, check the names with Object.hasOwn, and test an unknown role and an unknown action.
The tests copy the code's table, so they can never disagree with it.
Why it happens: It saved typing.
Fix: Type the expected table in the test from the agreed document. A change must then be made twice.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
A permission table for Ferngate
Ferngate Cycle Repairs has mechanics, the owner and a part-time bookkeeper. Write a permission table for five actions, mark every unknown cell as a decision, and write six table-driven test rows.
You will need
- Actions: record a part taken for a job; view stock levels; correct a stock count; set the low-stock threshold; view all jobs.
- Roles: mechanic, owner, bookkeeper.
- Note: the low-stock threshold is still "to be agreed" with the owner.
- Note: the owner has not said whether a mechanic may edit an entry another mechanic made.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Ask who should be able to change a stock count. A wrong count can hide a theft or cause a wrong reorder.
- "Own" needs a record that says who created it. Check that the data model keeps that.
Show a model answer
A strong answer gives mechanics 'any' for recording a part and viewing stock, and 'own' for editing a recorded part, pending the owner's decision. Only the owner corrects stock counts or sets the threshold, and the threshold stays a decision because the owner has not agreed it. The bookkeeper might view stock and jobs but change nothing, which is least privilege. The ownership row relies on the part record storing the mechanic who made it, which is a data-model point. The six tests include a mechanic who may not correct stock, an owner who may, an unknown role and an unknown action. The answer never invents the threshold or the editing rule.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. Own means the permission is allowed, within the person's own records. The handler narrows the query with the clinician from the session. Returning everything is tempting because the action is allowed, but it ignores the limit. 403 would wrongly block something the role may do.
Show the answer and explanation
Answer: B. Deny by default means anything the table does not know gets no access. Guessing the intent is tempting, but a guess can grant access nobody agreed to. The CHECK rule on the role column should stop such a value from being stored in the first place.
Show the answer and explanation
Answer: B. A test that reads the code's own table agrees with it whatever it says, so it can never catch a change. Two separate copies force a deliberate change in both places. Tests can import code, which is why the last option sounds possible but is wrong.
Frequently asked questions
What is role-based access control?
It is a way of deciding what people may do by giving each person a role, and giving each role a set of permissions. A physiotherapist and a front-desk member can sign in to the same system and still see different things. It is simple to explain, review and test.
Where should permission checks go in my code?
Keep the rules in one place, as a table and one function. Call that function from every handler on the server. The interface may also use it to hide buttons, but the server check is the one that counts.
What does deny by default mean?
If the rules do not mention a role or an action, the answer is no. This way a mistake, such as a forgotten row or a misspelt role, locks something instead of opening it. It is much safer to fix a wrongly refused request than a wrongly allowed one.
How do I test permissions?
Write the expected table in the test, by hand, from the agreed document. Then check every role against every action, and add cases for unknown roles, unknown actions and ownership. A change to a permission then breaks a test until someone updates both copies on purpose.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Authorization Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Least privilege, deny by default, and enforcing permissions on every request.
- 5.5. Constraints(opens in a new tab)
PostgreSQL Global Development Group · Official documentation · CHECK, UNIQUE and foreign key rules, as used in migration 004.
- Test runner(opens in a new tab)
Node.js · Official documentation · The built-in test runner used for the permission tests. Check the docs for your Node version.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.