From 6fc120aca6062f96725adaece85a7b76000affda Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Tue, 31 Jan 2023 14:13:35 +0300 Subject: auth: Retrieve group members. --- gn3/auth/authorisation/groups.py | 12 ++++++++++++ gn3/auth/authorisation/views.py | 14 ++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) (limited to 'gn3') diff --git a/gn3/auth/authorisation/groups.py b/gn3/auth/authorisation/groups.py index 0e022ee..c691457 100644 --- a/gn3/auth/authorisation/groups.py +++ b/gn3/auth/authorisation/groups.py @@ -209,3 +209,15 @@ def add_user_to_group(cursor: db.DbCursor, the_group: Group, user: User): ("INSERT INTO group_users VALUES (:group_id, :user_id) " "ON CONFLICT (group_id, user_id) DO NOTHING"), {"group_id": str(the_group.group_id), "user_id": str(user.user_id)}) + +def group_users(conn: db.DbConnection, group_id: UUID) -> Iterable[User]: + """Retrieve all users that are members of group with id `group_id`.""" + with db.cursor(conn) as cursor: + cursor.execute( + "SELECT u.* FROM group_users AS gu INNER JOIN users AS u " + "ON gu.user_id = u.user_id WHERE gu.group_id=:group_id", + {"group_id": str(group_id)}) + results = cursor.fetchall() + + return (User(UUID(row["user_id"]), row["email"], row["name"]) + for row in results) diff --git a/gn3/auth/authorisation/views.py b/gn3/auth/authorisation/views.py index 6cab0df..03c4b03 100644 --- a/gn3/auth/authorisation/views.py +++ b/gn3/auth/authorisation/views.py @@ -15,7 +15,7 @@ from .resources import user_resources as _user_resources from .roles import user_role, assign_default_roles, user_roles as _user_roles from .groups import ( all_groups, GroupCreationError, user_group as _user_group, - create_group as _create_group) + group_users as _group_users, create_group as _create_group) from ..authentication.oauth2.resource_server import require_oauth from ..authentication.users import save_user, set_user_password @@ -162,7 +162,7 @@ def role(role_id: uuid.UUID) -> Response: __error__, lambda a_role: jsonify(dictify(a_role))) @oauth2.route("/user-group", methods=["GET"]) -@require_oauth("group") +@require_oauth("profile group") def user_group(): """Retrieve the group in which the user is a member.""" with require_oauth.acquire("profile group") as the_token: @@ -185,3 +185,13 @@ def user_resources(): return jsonify([ dictify(resource) for resource in _user_resources(conn, the_token.user)]) + +@oauth2.route("/group-users/", methods=["GET"]) +@require_oauth("profile group") +def group_users(group_id: uuid.UUID) -> Response: + """Retrieve all the members of a group.""" + with require_oauth.acquire("profile group") as the_token: + db_uri = current_app.config["AUTH_DB"] + with db.connection(db_uri) as conn: + return jsonify(tuple( + dictify(user) for user in _group_users(conn, group_id))) -- cgit v1.2.3