|
| 1 | +"""Split apikeys scope into create and delete |
| 2 | +
|
| 3 | +Revision ID: d829476bc173 |
| 4 | +Revises: 27e069ba3bf5 |
| 5 | +Create Date: 2025-12-08 17:09:18.062287 |
| 6 | +
|
| 7 | +""" |
| 8 | +from alembic import op |
| 9 | +from sqlalchemy.orm.session import Session |
| 10 | + |
| 11 | +from tiled.authn_database.orm import Role |
| 12 | + |
| 13 | +# revision identifiers, used by Alembic. |
| 14 | +revision = "d829476bc173" |
| 15 | +down_revision = "27e069ba3bf5" |
| 16 | +branch_labels = None |
| 17 | +depends_on = None |
| 18 | + |
| 19 | + |
| 20 | +ROLES = ["admin", "user"] |
| 21 | +NEW_SCOPES_USER = ["create:apikeys", "revoke:apikeys", "create:node"] |
| 22 | +OLD_SCOPES_USER = ["apikeys", "create"] |
| 23 | +NEW_SCOPES_ADMIN = ["create:node"] |
| 24 | +OLD_SCOPES_ADMIN = ["create"] |
| 25 | + |
| 26 | + |
| 27 | +def upgrade(): |
| 28 | + """ |
| 29 | + Add new scopes to Roles. |
| 30 | + Remove old scopes from Roles, if present. |
| 31 | + """ |
| 32 | + connection = op.get_bind() |
| 33 | + with Session(bind=connection) as db: |
| 34 | + for role_name in ROLES: |
| 35 | + role = db.query(Role).filter(Role.name == role_name).first() |
| 36 | + scopes = role.scopes.copy() |
| 37 | + if role_name == "admin": |
| 38 | + NEW_SCOPES = NEW_SCOPES_ADMIN |
| 39 | + OLD_SCOPES = OLD_SCOPES_ADMIN |
| 40 | + else: |
| 41 | + NEW_SCOPES = NEW_SCOPES_USER |
| 42 | + OLD_SCOPES = OLD_SCOPES_USER |
| 43 | + for scope in OLD_SCOPES: |
| 44 | + if scope in scopes: |
| 45 | + scopes.remove(scope) |
| 46 | + scopes.extend(NEW_SCOPES) |
| 47 | + role.scopes = scopes |
| 48 | + db.commit() |
| 49 | + |
| 50 | + |
| 51 | +def downgrade(): |
| 52 | + """ |
| 53 | + Remove new scopes from Roles, if present. |
| 54 | + Add old scopes to Roles, if not preesent. |
| 55 | + """ |
| 56 | + connection = op.get_bind() |
| 57 | + with Session(bind=connection) as db: |
| 58 | + for role_name in ROLES: |
| 59 | + role = db.query(Role).filter(Role.name == role_name).first() |
| 60 | + scopes = role.scopes.copy() |
| 61 | + if role_name == "admin": |
| 62 | + NEW_SCOPES = NEW_SCOPES_ADMIN |
| 63 | + OLD_SCOPES = OLD_SCOPES_ADMIN |
| 64 | + else: |
| 65 | + NEW_SCOPES = NEW_SCOPES_USER |
| 66 | + OLD_SCOPES = OLD_SCOPES_USER |
| 67 | + for scope in NEW_SCOPES: |
| 68 | + if scope in scopes: |
| 69 | + scopes.remove(scope) |
| 70 | + for scope in OLD_SCOPES: |
| 71 | + if scope not in scopes: |
| 72 | + scopes.append(scope) |
| 73 | + role.scopes = scopes |
| 74 | + db.commit() |
0 commit comments