Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

12.4 KB
Raw Blame

description: How user, employee, employeeJob, company membership, and permissions/claims relate in Carbon's auth identity graph paths: - "packages/database/supabase/migrations/" - "packages/auth/src/services/" - "apps/erp/app/modules/users/" - "apps/erp/app/modules/resources/"

User / Employee / EmployeeJob / Permission identity graph

Carbon's identity is multi-tenant: one user can belong to many companies, with a per-company role and per-company employee record. "Job" in employeeJob means an employee's job title/role within a company — NOT a production/manufacturing job (that is the separate job table from 20240909194622_jobs.sql).

Core tables (PK + key columns; newest migrations applied)

  • user — global identity, id matches Supabase auth.users.id. PK id.
    • email, firstName, lastName, fullName (GENERATED firstName || ' ' || lastName, STORED), about (default ''), avatarUrl, active (default TRUE), phone, admin, developer, isConsoleOperator, flags JSONB, acknowledgedITAR, externalId JSONB, createdAt, updatedAt.
    • No FKs to other app tables. fullName is generated and never null when names are set; prefer it directly.
  • userToCompany — the membership join table. PK (userId, companyId). role "role" where CREATE TYPE "role" AS ENUM ('customer','employee','supplier'). This is how a user belongs to multiple companies (one row per company, role can differ per company).
  • employee — per-company employee record. PK (id, companyId); id → user.id. employeeTypeId → employeeType.id (RESTRICT), companyId → company.id, active BOOLEAN DEFAULT FALSE, pin (console mode). Added in 20241208004151_invites.sql.
  • employeeJob — job title / org placement. PK (id, companyId); id → user.id. title, startDate DATE, locationId → location.id, departmentId → department.id, shiftId → shift.id, managerId → user.id, tags TEXT[], customFields JSONB, updatedAt, updatedBy → user.id. Created 20230224035103_shifts.sql; departmentId/tags added later. (workCellId existed briefly, then dropped in 20240819115702_work-centers.sql.)
  • employeeType — per-company role definition. PK id. name, companyId → company.id, protected BOOLEAN.
  • employeeTypePermission — permissions granted by an employee type. PK (employeeTypeId, module). module "module" (enum), and view/create/update/delete TEXT[] (each is an array of company IDs; "0" = all companies). employeeTypeId → employeeType.id.
  • userPermission — the effective, flattened per-user permission set. PK id (id → user.id). permissions JSONB DEFAULT '{}' keyed like <module>_<action> → array of company IDs.

How permissions / claims are derived

  1. Membership: userToCompany gives the user's role in a company.
  2. Grants: employee.employeeTypeId → employeeType → employeeTypePermission defines what each employee type can do per module/action, scoped to company IDs.
  3. Flattened: those grants are materialized into userPermission.permissions (JSONB, <module>_<action> → company-ID array).
  4. Claims: SQL get_claims(uid, company) (latest: 20260925121735_rpc-function-guards.sql) reads role from userToCompany and permissions from userPermission, then returns (jsonb_build_object('role', role) || permissions). Called through the API it answers only for the caller's own uid, or for someone in a company where the caller holds users_view or users_update; service role and direct connections are unrestricted. RLS helpers like get_companies_with_employee_role(), and get_companies_with_employee_permission('<module>_<action>') enforce this in policies (helpers re-defined in later migrations — read the newest).
  5. App layer (packages/auth/src/services/): getUserClaims() caches claims in Redis at permissions:${userId} (falls back to the RPC); makePermissionsFromClaims() (users.ts) parses them into { permissions, role }; requirePermissions(request, { view?, create?, update?, delete?, role? }) in auth.server.ts is the route gate. Active company comes from a companyId cookie via getCompanyId/setCompanyId (company.server.ts).

Views (read-only joins)

  • employees — newest in 20260529160000_employees-view-status.sql. Joins user + employee (+ employeeJob/location for locationId, locationName). Aliases fullName AS "name". Adds a computed status ('Active' | 'Invited' | 'Inactive') from employee.active and the invite table. Filter is WHERE u.active = TRUE (on user, not employee), so inactive employees of an active user still appear — filter on active/status when you only want active employees.
  • employeeSummary — 20240103010721_employee-summary.sql. user + employee + LEFT JOIN employeeJob/location/department/manager user. Returns id, name, avatarUrl, companyId, title, startDate, departmentName, locationName, managerName.
  • employeesAcrossCompanies — 20260526091437_employee-location.sql. Aggregates companyId per user (array_agg) for users across companies.

Gotchas

  • user RLS is company-scoped (20260924153817_user-rls-company-scope.sql). A caller sees themselves, users who share a userToCompany company, and, as an employee, users with an employee / customerAccount / supplierAccount row in their company (pending invites, deactivated people). Another user's row is writable only with users_update in a company where that user has an active userToCompany row. INSERT and DELETE are revoked from anon/authenticated, so they go through the service role. A BEFORE UPDATE trigger (guard_user_identity_columns) rejects any API-role change to id, email, active, admin, developer or isConsoleOperator. Sending those columns unchanged is fine. Deleting a user also deletes its identity group (sync_delete_user_identity_group).
  • employee and employeeJob share composite PK (id, companyId) and id → user.id — always scope queries by both id and companyId. A user has one employee/employeeJob row per company.
  • userToCompany.role (membership type) is distinct from employeeType (which permission set); don't conflate "role" the enum with "role" the job title (employeeJob.title).
  • Permission company-ID array "0" means "all companies" — don't string-match a literal company id only.
  • Deactivating an employee (deactivateEmployee in packages/auth/src/services/users.server.ts) removes the company from userPermission.permissions, deletes the userToCompany row and every membership in groups owned by that company, and sets employee.active = false. It does not clear user.active, delete the employee or employeeJob rows, or scrub stored userId references (assignee columns, workCenterEmployee, notification-group settings arrays).
  • The claims cache is invalidated by the deactivate* functions themselves, not by their callers. deactivateEmployee/Customer/Supplier each redis.del(getPermissionCacheKey(userId)) on success, and deactivateUser deletes it again after delegating. That matters because requirePermissions reads the cache (1h TTL) before the database, and the create*Account rollback paths in the ERP call the role-specific functions directly rather than going through deactivateUser — a caller that skipped the invalidation would leave revoked grants live. employeeJob is kept on purpose — it is org placement, not access — so title, start date, department, shift, manager, location, tags and custom fields survive a deactivate/re-invite round trip. Group memberships do not: acceptance restores only the employee-type group, so a re-invited person must be added back to any custom group by hand. Because the row survives, a reader of employeeJob that means "current staff" must also check employee.active (getScheduledEmployeesToday does; employeeJob has no FK to employee to embed).
  • Planning stores more user ids the deactivation does not scrub: itemPlanning.responsibleEmployee, location.responsibleEmployee, companySettings.defaultResponsibleEmployee, itemPostingGroupResponsibility.responsibleEmployee and planningAction.assignee (all TEXT REFERENCES "user"("id"), so the database accepts any user's id, including another company's). A route saves one only after isActiveCompanyEmployee(client, companyId, userId) (apps/erp/app/modules/shared/shared.service.ts), which fails closed on a read error.
  • Re-adding a deactivated person through Add Account (createEmployeeAccount) reuses the surviving rows rather than failing: it refuses only when the existing employee row is active. A person whose invite is still pending is re-added the same way, which issues a new code and invalidates the link already emailed. The reuse path (reinviteDeactivatedEmployee) is one Kysely transaction: it locks the employee row and re-checks active under the lock, updates employeeTypeId, upserts employeeJob (only locationId, updatedBy and updatedAt on conflict) and upserts the invite on (email, companyId) — so the invite's permissions and the row's employee type cannot diverge, and a failed write leaves no redeemable invite. It never inserts a first-time employee row; that stays under the caller's RLS client.
  • The re-add writes outside RLS, so it checks what RLS would have. The route requires only users_create, but a first-time add inserts employee and employeeJob under the caller's client, whose INSERT policies require users_update and people_create. Before the reuse transaction, createEmployeeAccount reads the inviter's claims (getUserClaims) and refuses unless both are held — otherwise a users_create-only admin could re-add someone they could never have added. The writes stamp the inviter in updatedBy (employeeJob, invite) because the Kysely connection has no auth.uid() for the audit log; employee has no audit columns.
  • A re-used invite row restarts createdAt (insertInvite and the reuse path both set it). The controlled-environment expiry (isControlledInviteExpired) counts from it, and the reused row is the person's original invite, so keeping it expired the new invite on arrival.
  • Re-activation happens on invite acceptance — acceptInvite (apps/erp/app/modules/users/users.service.ts) restores the employee-type membership the deactivation removed (the sync_add_employee_to_type_group trigger fires on INSERT only, so an UPDATE cannot rely on it), flips active back to true, and stamps acceptedAt in one Kysely transaction, so a failed restore leaves the invite unaccepted and retryable rather than an active employee outside their type's group. The acceptedAt update also requires revokedAt IS NULL, so a revoke that commits after the invite was looked up still wins. Before merging userPermission, the transaction locks the user row FOR NO KEY UPDATE (migrateUserToSso does the same), so two first acceptances for one user in different companies cannot drop each other's grants. The membership insert uses ON CONFLICT ("groupId", "memberUserId") DO NOTHING against membership_groupId_memberUserId_key (20261015074817), which is what makes it safe against the trigger racing the same insert.
  • Every writer of a user membership must tolerate that index. Before it, uq_membership (groupId, memberGroupId, memberUserId) never deduped user memberships (memberGroupId is NULL on all of them), so duplicates were silent. The insert interceptors (sync_add_employee_to_type_group, sync_add_customer_account_to_group, sync_add_supplier_account_to_group) use ON CONFLICT … DO NOTHING, and sync_update_employee_type_membership drops the old membership instead of moving it when the user is already in the new type's group (20261015075112). A new writer needs the same, or a leftover membership fails the insert or update that fired it.
  • Notification fan-out (notify.ts resolve-recipients in packages/jobs) filters resolved recipients against userToCompany for the notification's company — a missing membership row (i.e. a deactivated user) is dropped before any in-app/email/Slack delivery, regardless of how the recipient list was built.
  • Permission/claims helper SQL functions are redefined across many migrations — always read the newest.