Abdulkader Safi

From owner and member to editable roles and teams in a CRM built in Rust

How Private CRM went from two hard-coded roles to editable roles, record scoping and manager hierarchies, plus the PostgreSQL sequence bug on the way.

5 min read

Share
Roles page of a CRM built in Rust listing permissions with checkboxes next to a team hierarchy diagram

The first version of Private CRM had two kinds of people: the owner and members. By the end of day one that was gone, replaced by roles you edit on a page, permissions copied onto each user, and managers who can see their team's deals.

This post covers how access control grew in four steps, the leaks I closed along the way, and one PostgreSQL bug that SQLite never showed.

Step one: owner, member and no public sign-up

The first access commit closed public registration. The owner invited members from a Users page, and the invite was a password reset link. Users and API tokens were owner-only.

That lasted under an hour. Mail wasn't set up yet, so links sent by email were a problem. The next change let the owner set a member's password directly. No email needed. The owner could also edit a user or disable them, and a disabled user can't log in. Their sessions and their API tokens stop working too, which matters once AI agents hold tokens (part 5).

Step two: every record gets an owner

Then the "customers" table split into contacts and companies, and every contact, company and deal got an owner. Members saw only what they owned. The owner saw everything. That rule had to hold in three places at once: the pages, the dashboard and the MCP server.

Writing the rule once is easy. Finding every place a record leaks through a side door took a second commit:

  • A contact could be linked to any company id, even one the user couldn't see. Now the link is refused.
  • A contact page showed its company even when the viewer couldn't open that company. Now it's hidden.
  • Orders were visible to anyone. Now they follow the contact they belong to.
  • Company websites must be http or https links, so the link on the company page can't run script.

That last one isn't about access, but it came out of the same pass: anything a member types ends up on someone else's screen.

Step three: roles are a name and a list

Hard-coding "owner" and "member" stopped working once people wanted something in between. So a role became a name plus a list of permissions, edited on a Roles page. Two were seeded: Admin with everything, Member with products and orders. The existing owner became Admin.

The permissions today are: see everyone's records, see their team's records, manage products, manage orders, archive and restore, manage users and roles, change settings, read the activity log, and use the API and MCP. Nobody can remove their own access to users and roles, so you can't lock yourself out by accident.

The interesting decision was where to keep them. Each user keeps a copy of their role's permissions. When a role changes, its users get rewritten. Why bother? Because a visibility check then needs no database call:

pub fn sees_all(&self) -> bool { /* checks the copied permissions */ }

pub fn owners(&self) -> Vec<i64> {
    let mut owners = vec![self.id];
    if self.can(Permission::SeeTeam) {
        owners.extend(&self.team.0);
    }
    owners
}

pub fn can_see(&self, owner_id: Option<i64>) -> bool {
    self.sees_all() || owner_id.is_some_and(|id| self.owners().contains(&id))
}

Policies call can_see all over the place, including inside loops that build lists. Keeping it synchronous kept them simple.

Step four: teams and managers

Next request: a sales lead should see their team's deals. Users got a manager ("Reports to") on the Users page, and the see_team permission lets a role see the records of everyone below them, at any depth. A team manager sees their leads' records and the records of the people under those leads.

Same trick as permissions: each user stores the ids of everyone below them in a JSON column, rebuilt whenever someone's manager changes. The rebuild walks the whole users table. There's a comment in the code admitting it:

// ponytail: walks the whole users table, fine for a company-sized team list.

That's a deliberate ceiling. A CRM for one company has dozens of users, not millions. Two guard rails: nobody can report to themselves, and nobody can report to someone in their own team, because that would make a loop.

The activity log needed the same treatment a commit later. A reader who doesn't see everyone's records now gets only their own log lines, plus their team's if their role allows it. Without that, the log would show the old and new values of records they can't open.

The PostgreSQL bug SQLite hid

I develop on SQLite and run PostgreSQL in production. The roles migration inserted Admin and Member with fixed ids 1 and 2. On SQLite, fine. On PostgreSQL, creating the first new role failed with a duplicate key on id 1.

PostgreSQL hands out ids from a sequence, and inserting explicit ids doesn't move it. The fix is one statement, run only on PostgreSQL:

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
    if let Driver::Postgres = tx.driver() {
        tx.query("select setval(pg_get_serial_sequence('roles', 'id'), (select max(id) from roles))")
            .statement()
            .await?;
    }
    Ok(())
}

After that commit the full suite passed on both databases. If you seed rows with fixed ids anywhere, check this before your first production insert. I wrote more about why SQLite is enough for most projects, but this is the kind of gap that only shows up when you switch.

Small fixes that came with it

  • Emails are stored lowercase and sign-in lowercases what was typed. The password stays case-sensitive.
  • A member who opens someone else's record gets a 403, on every page and over MCP.
  • Revoking your own leaked API token no longer needs the archive permission (more on that in part 3).

What I'd do again

Give every record an owner from the first migration, and write the visibility rule as one function that every page and every API path calls. Then go hunting for side doors: linked records, counts on dashboards, activity logs. For more on getting the basics right, see why your auth system is probably wrong.

Part 3 covers the other half of the same idea: nothing in Private CRM is ever deleted, and everything is logged.

Last updated 4 Dec 2026 · filed under Laravel, rust, crm

Every entry on this project

12 build notes, in order

Including the ones where nothing worked. You are on part 2.

Read the series →

FAQ

Frequently asked questions

How should a small CRM decide who can see which records?

Private CRM gives every contact, company and deal an owner. A user whose role has "see everyone's records" sees all of them; anyone else sees what they own, plus what their team owns if their role has "see their team's records". Orders follow the contact they belong to. The same rule runs in the browser, on the dashboard and over MCP.

Why does PostgreSQL give a duplicate key error after inserting rows with fixed ids?

PostgreSQL hands out ids from a sequence, and inserting rows with explicit ids doesn't move that sequence. The next insert without an id gets 1 and collides. The fix is to run select setval(pg_get_serial_sequence('roles', 'id'), (select max(id) from roles)) after seeding. SQLite picks the next id from the table, so it never shows the bug.

Should permissions be stored on the user or looked up from the role?

Private CRM stores a copy of the role's permissions on each user and rewrites those copies whenever the role changes. That keeps permission checks synchronous and free of queries, at the cost of keeping copies in step. For a company-sized user list that tradeoff is cheap.

How do you model a manager who sees their whole team's records?

Each user has an optional manager. Private CRM stores, on each user, the ids of everyone below them at any depth, and rebuilds those lists whenever a manager changes. A role with "see their team's records" then checks the record owner against that list. Nobody can report to themselves or to someone in their own team.

Written by

Abdulkader Safi

Software Engineer

Lead engineer at DSRPT, from Lebanon and based in Kuwait. I write about the tools and bugs from real client work, with the numbers I measured.

About me → GitHub LinkedIn

Need this kind of work done on your project?

Start a project →

Keep reading

More from Private CRM: an AI CRM where Claude does the data entry and you make the calls

All 12 entries →