64 lines
1.7 KiB
Python
64 lines
1.7 KiB
Python
from sqlalchemy import delete, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.permission import Permission
|
|
|
|
|
|
class PermissionsRepository:
|
|
def __init__(self, db: Session) -> None:
|
|
self.db = db
|
|
|
|
def list_by_user_id(self, user_id: str) -> list[Permission]:
|
|
stmt = select(Permission).where(Permission.user_id == user_id)
|
|
return list(self.db.scalars(stmt).all())
|
|
|
|
def create_if_not_exists(
|
|
self,
|
|
user_id: str,
|
|
scope_type: str,
|
|
scope_id: str,
|
|
module: str,
|
|
action: str,
|
|
) -> Permission:
|
|
stmt = select(Permission).where(
|
|
Permission.user_id == user_id,
|
|
Permission.scope_type == scope_type,
|
|
Permission.scope_id == scope_id,
|
|
Permission.module == module,
|
|
Permission.action == action,
|
|
)
|
|
existing = self.db.scalar(stmt)
|
|
if existing:
|
|
return existing
|
|
|
|
item = Permission(
|
|
user_id=user_id,
|
|
scope_type=scope_type,
|
|
scope_id=scope_id,
|
|
module=module,
|
|
action=action,
|
|
)
|
|
self.db.add(item)
|
|
self.db.commit()
|
|
self.db.refresh(item)
|
|
return item
|
|
|
|
def revoke(
|
|
self,
|
|
user_id: str,
|
|
scope_type: str,
|
|
scope_id: str,
|
|
module: str,
|
|
action: str,
|
|
) -> int:
|
|
stmt = delete(Permission).where(
|
|
Permission.user_id == user_id,
|
|
Permission.scope_type == scope_type,
|
|
Permission.scope_id == scope_id,
|
|
Permission.module == module,
|
|
Permission.action == action,
|
|
)
|
|
result = self.db.execute(stmt)
|
|
self.db.commit()
|
|
return int(result.rowcount or 0)
|