From 2be81e59ff416cb8764aaf041a3b8febae4d8875 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Thu, 8 Dec 2022 06:22:23 +0300 Subject: auth: add function to retrieve a user's group * gn3/auth/authorisation/groups.py: new `user_group` function * tests/unit/auth/test_groups.py: test `user_group` function --- gn3/auth/authorisation/groups.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'gn3') diff --git a/gn3/auth/authorisation/groups.py b/gn3/auth/authorisation/groups.py index 6496e87..743e812 100644 --- a/gn3/auth/authorisation/groups.py +++ b/gn3/auth/authorisation/groups.py @@ -106,3 +106,21 @@ def authenticated_user_group(conn) -> Maybe: return Just(groups[0]) return Nothing + +def user_group(conn: db.DbConnection, user: User) -> Maybe: + """Returns the given user's group""" + with db.cursor(conn) as cursor: + cursor.execute( + ("SELECT groups.group_id, groups.group_name FROM group_users " + "INNER JOIN groups ON group_users.group_id=groups.group_id " + "WHERE group_users.user_id = ?"), + (str(user.user_id),)) + groups = tuple(Group(UUID(row[0]), row[1]) for row in cursor.fetchall()) + + if len(groups) > 1: + raise MembershipError(user, groups) + + if len(groups) == 1: + return Just(groups[0]) + + return Nothing -- cgit v1.2.3