-- +goose Up CREATE TABLE invitations ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, email citext NOT NULL, role_id uuid NOT NULL REFERENCES roles (id) ON DELETE CASCADE, token_hash bytea NOT NULL UNIQUE, invited_by uuid REFERENCES users (id) ON DELETE SET NULL, expires_at timestamptz NOT NULL, accepted_at timestamptz, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX invitations_org_idx ON invitations (org_id); ALTER TABLE invitations ENABLE ROW LEVEL SECURITY; ALTER TABLE invitations FORCE ROW LEVEL SECURITY; CREATE POLICY invitations_tenant ON invitations FOR ALL USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id()); -- Invitees are not members yet; see api_token_org for the pattern. -- +goose StatementBegin CREATE FUNCTION invitation_org(hash bytea) RETURNS uuid LANGUAGE plpgsql VOLATILE AS $$ DECLARE prev text := coalesce(current_setting('app.scope', true), ''); result uuid; BEGIN PERFORM set_config('app.scope', 'system', true); SELECT org_id INTO result FROM invitations WHERE token_hash = hash; PERFORM set_config('app.scope', prev, true); RETURN result; END $$; -- +goose StatementEnd -- +goose Down DROP FUNCTION invitation_org(bytea); DROP TABLE invitations;