65 lines
2.1 KiB
Python
65 lines
2.1 KiB
Python
"""protected super admin account
|
|
|
|
Adds `user.is_superadmin`. A trigger refuses to delete such a row, to deactivate it, or
|
|
to change its role, email, employee code or the flag itself, so the protection holds even
|
|
for a direct SQL session. (The password hash stays changeable so the owner can rotate it
|
|
with `scripts/create_superadmin.py`.)
|
|
|
|
Revision ID: t0d6f2b8c5e7
|
|
Revises: s9c5e1a7b4d6
|
|
Create Date: 2026-10-27
|
|
"""
|
|
|
|
from collections.abc import Sequence
|
|
|
|
import sqlalchemy as sa
|
|
|
|
from alembic import op
|
|
|
|
revision: str = "t0d6f2b8c5e7"
|
|
down_revision: str | None = "s9c5e1a7b4d6"
|
|
branch_labels: str | Sequence[str] | None = None
|
|
depends_on: str | Sequence[str] | None = None
|
|
|
|
|
|
def upgrade() -> None:
|
|
op.add_column(
|
|
"user",
|
|
sa.Column("is_superadmin", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
|
)
|
|
op.execute(
|
|
"""
|
|
CREATE OR REPLACE FUNCTION protect_superadmin() RETURNS trigger AS $$
|
|
BEGIN
|
|
IF TG_OP = 'DELETE' THEN
|
|
IF OLD.is_superadmin THEN
|
|
RAISE EXCEPTION 'The super admin account cannot be deleted';
|
|
END IF;
|
|
RETURN OLD;
|
|
END IF;
|
|
IF OLD.is_superadmin AND (
|
|
NEW.is_superadmin IS DISTINCT FROM OLD.is_superadmin
|
|
OR NEW.is_active IS DISTINCT FROM OLD.is_active
|
|
OR NEW.role IS DISTINCT FROM OLD.role
|
|
OR NEW.email IS DISTINCT FROM OLD.email
|
|
OR NEW.employee_code IS DISTINCT FROM OLD.employee_code
|
|
OR NEW.full_name IS DISTINCT FROM OLD.full_name
|
|
) THEN
|
|
RAISE EXCEPTION 'The super admin account cannot be modified';
|
|
END IF;
|
|
RETURN NEW;
|
|
END;
|
|
$$ LANGUAGE plpgsql;
|
|
"""
|
|
)
|
|
op.execute(
|
|
'CREATE TRIGGER trg_protect_superadmin BEFORE UPDATE OR DELETE ON "user" '
|
|
"FOR EACH ROW EXECUTE FUNCTION protect_superadmin()"
|
|
)
|
|
|
|
|
|
def downgrade() -> None:
|
|
op.execute('DROP TRIGGER IF EXISTS trg_protect_superadmin ON "user"')
|
|
op.execute("DROP FUNCTION IF EXISTS protect_superadmin()")
|
|
op.drop_column("user", "is_superadmin")
|