aboutsummaryrefslogtreecommitdiff
path: root/gn3/auth/authorisation/groups.py
diff options
context:
space:
mode:
authorFrederick Muriuki Muriithi2022-11-24 13:42:37 +0300
committerFrederick Muriuki Muriithi2022-11-24 13:52:29 +0300
commit021b8dfcb99928b363e4546f626e3deb5793e392 (patch)
tree107182d01dc7e5fd802fadb4e12cd88867748c36 /gn3/auth/authorisation/groups.py
parentbac3865f7c0d625f2932e1c3fb001cc6a0048921 (diff)
downloadgenenetwork3-021b8dfcb99928b363e4546f626e3deb5793e392.tar.gz
auth: Implement `create_resource` function
* gn3/auth/authentication/checks.py: new `authenticated_p` decorator to apply on any function that requires the user to be authenticated before it runs. * gn3/auth/authorisation/checks.py: use a `auth.authentication.users.User` object rather than a UUID object in the global `g`. * gn3/auth/authorisation/groups.py: Implement the `authenticated_user_group` function to get the group(s) in which the currently authenticated user belongs. * gn3/auth/authorisation/resources.py: Implement the `create_resource` function correctly. * tests/unit/auth/conftest.py: extract the User objects into a global variable for reusability with the tests. * tests/unit/auth/test_resources.py: Use global user objects from conftest in the tests. Set a User object (rather than UUID) in the global `g` variable.
Diffstat (limited to 'gn3/auth/authorisation/groups.py')
-rw-r--r--gn3/auth/authorisation/groups.py30
1 files changed, 29 insertions, 1 deletions
diff --git a/gn3/auth/authorisation/groups.py b/gn3/auth/authorisation/groups.py
index 7597a04..ac80089 100644
--- a/gn3/auth/authorisation/groups.py
+++ b/gn3/auth/authorisation/groups.py
@@ -2,12 +2,16 @@
from uuid import UUID, uuid4
from typing import Sequence, Iterable, NamedTuple
+from flask import g
+from pymonad.maybe import Just, Maybe, Nothing
+
from gn3.auth import db
from gn3.auth.authentication.users import User
+from gn3.auth.authentication.checks import authenticated_p
+from .checks import authorised_p
from .privileges import Privilege
from .roles import Role, create_role
-from .checks import authorised_p
class Group(NamedTuple):
"""Class representing a group."""
@@ -75,3 +79,27 @@ def create_group_role(
(str(group_role_id), str(group.group_id), str(role.role_id)))
return GroupRole(group_role_id, role)
+
+@authenticated_p
+def authenticated_user_group(conn) -> Maybe:
+ """
+ Returns the currently authenticated user's group.
+
+ Look into returning a Maybe object.
+ """
+ user = g.user
+ 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