From 2344e4cd55cc37dac93ab2127a456a39dc4fedbe Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Mon, 12 Dec 2022 13:31:06 +0300 Subject: auth: Add a way to check whether a user is a group leader * gn3/auth/authorisation/groups.py: Add `is_group_leader` function --- gn3/auth/authorisation/groups.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'gn3/auth/authorisation') diff --git a/gn3/auth/authorisation/groups.py b/gn3/auth/authorisation/groups.py index dbc9f7d..cb32f00 100644 --- a/gn3/auth/authorisation/groups.py +++ b/gn3/auth/authorisation/groups.py @@ -124,3 +124,22 @@ def user_group(cursor: db.DbCursor, user: User) -> Maybe: return Just(groups[0]) return Nothing + +def is_group_leader(cursor: db.DbCursor, user: User, group: Group): + """Check whether the given `user` is the leader of `group`.""" + ugroup = user_group(cursor, user).maybe(False, lambda val: val) # type: ignore[misc] + if not group: + # User cannot be a group leader if not a member of ANY group + return False + + if not ugroup == group: + # User cannot be a group leader if not a member of THIS group + return False + + cursor.execute( + ("SELECT roles.role_name FROM user_roles LEFT JOIN roles " + "ON user_roles.role_id = roles.role_id WHERE user_id = ?"), + (str(user.user_id),)) + role_names = tuple(row[0] for row in cursor.fetchall()) + + return "group-leader" in role_names -- cgit v1.2.3