Stage 3 · Build
Advanced Auth & Tenant Security
Multi-Tenant Identity
Model organizations, memberships, tenant-scoped roles, invite flows, and ownership checks in PostgreSQL.
Why Multi-Tenant Identity
Multi-tenant applications serve multiple organizations from a single deployment. Each tenant's data must be isolated. Users can belong to multiple tenants with different roles. This requires careful identity modeling.
Data Model
CREATE TABLE organizations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE memberships (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
role VARCHAR(50) NOT NULL DEFAULT 'member',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE(user_id, org_id)
);
CREATE TABLE invitations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
email VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL DEFAULT 'member',
token VARCHAR(255) NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
accepted_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);Organizations are tenants. Memberships link users to organizations with roles. Invitations let existing members add new users. This is the foundation of multi-tenant identity.
Tenant-Scoped Queries
Invite Flows
Ownership Checks
Row-Level Security
-- Enable RLS on the projects table
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
-- Policy: users can only see projects in their organizations
CREATE POLICY org_isolation ON projects
FOR ALL
USING (org_id IN (
SELECT org_id FROM memberships WHERE user_id = current_setting('app.current_user_id')::uuid
));RLS enforces tenant isolation at the database level. Even if application code has a bug, the database prevents cross-tenant data access. This is defense in depth.
Never trust client-provided org IDs. Always verify the user is a member of the requested organization. Cross-tenant data access is a critical security vulnerability.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.