aboutsummaryrefslogtreecommitdiff
path: root/gn_auth/auth/authorisation
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2024-06-10 13:40:09 -0500
committerFrederick Muriuki Muriithi2024-06-10 13:40:09 -0500
commitf427b554c033b6c9d1d37fc420988a14fdc526a9 (patch)
tree18a0803c7802ac03b2059bfb767b8711a71d6135 /gn_auth/auth/authorisation
parent342933a0221aa0bbe0243e30d21cdfe5539bc269 (diff)
downloadgn-auth-f427b554c033b6c9d1d37fc420988a14fdc526a9.tar.gz
Provide functions to convert DB rows into data objects.
Diffstat (limited to 'gn_auth/auth/authorisation')
-rw-r--r--gn_auth/auth/authorisation/privileges.py8
-rw-r--r--gn_auth/auth/authorisation/roles/models.py23
2 files changed, 31 insertions, 0 deletions
diff --git a/gn_auth/auth/authorisation/privileges.py b/gn_auth/auth/authorisation/privileges.py
index fabab65..a977db5 100644
--- a/gn_auth/auth/authorisation/privileges.py
+++ b/gn_auth/auth/authorisation/privileges.py
@@ -2,6 +2,8 @@
from dataclasses import dataclass
from typing import Iterable
+import sqlite3
+
from ..db import sqlite3 as db
from ..authentication.users import User
@@ -13,6 +15,12 @@ class Privilege:
privilege_description: str
+def db_row_to_privilege(row: sqlite3.Row) -> Privilege:
+ "Convert single db row into a privilege object."
+ return Privilege(privilege_id=row["privilege_id"],
+ privilege_description=row["privilege_description"])
+
+
def user_privileges(conn: db.DbConnection, user: User) -> Iterable[Privilege]:
"""Fetch the user's privileges from the database."""
with db.cursor(conn) as cursor:
diff --git a/gn_auth/auth/authorisation/roles/models.py b/gn_auth/auth/authorisation/roles/models.py
index 3ec3316..53c0378 100644
--- a/gn_auth/auth/authorisation/roles/models.py
+++ b/gn_auth/auth/authorisation/roles/models.py
@@ -31,6 +31,29 @@ def check_user_editable(role: Role):
raise AuthorisationError(
f"The role `{role.role_name}` is not user editable.")
+
+def db_rows_to_roles(rows) -> tuple[Role, ...]:
+ """Convert a bunch of db rows into a bunch of `Role` objects."""
+ def __resultset_to_roles__(roles, row):
+ """Convert SQLite3 resultset into `Role` objects"""
+ _role = roles.get(row["role_id"])
+ return {
+ **roles,
+ row["role_id"]: Role(
+ role_id=UUID(row["role_id"]),
+ role_name=row["role_name"],
+ user_editable=bool(row["user_editable"]),
+ privileges=(
+ (_role.privileges if bool(_role) else tuple()) +
+ (Privilege(
+ privilege_id=row["privilege_id"],
+ privilege_description=row[
+ "privilege_description"]),)))
+ }
+
+ return tuple(reduce(__resultset_to_roles__, rows, {}).values()
+ if bool(rows) else [])
+
@authorised_p(
privileges = ("group:role:create-role",),
error_description="Could not create role")