aboutsummaryrefslogtreecommitdiff
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
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.
-rw-r--r--gn3/auth/authentication/checks.py14
-rw-r--r--gn3/auth/authorisation/checks.py4
-rw-r--r--gn3/auth/authorisation/groups.py30
-rw-r--r--gn3/auth/authorisation/resources.py24
-rw-r--r--tests/unit/auth/conftest.py25
-rw-r--r--tests/unit/auth/test_resources.py26
6 files changed, 94 insertions, 29 deletions
diff --git a/gn3/auth/authentication/checks.py b/gn3/auth/authentication/checks.py
new file mode 100644
index 0000000..63b0752
--- /dev/null
+++ b/gn3/auth/authentication/checks.py
@@ -0,0 +1,14 @@
+"""Functions to check for user authentication."""
+
+from flask import g
+
+from .exceptions import AuthenticationError
+
+def authenticated_p(func):
+ """Decorator for functions requiring authentication."""
+ def __authenticated__(*args, **kwargs):
+ user = g.user if hasattr(g, "user") else False
+ if user:
+ return func(*args, **kwargs)
+ raise AuthenticationError("You need to be authenticated")
+ return __authenticated__
diff --git a/gn3/auth/authorisation/checks.py b/gn3/auth/authorisation/checks.py
index 3181655..dd041fe 100644
--- a/gn3/auth/authorisation/checks.py
+++ b/gn3/auth/authorisation/checks.py
@@ -16,11 +16,11 @@ def authorised_p(
def __build_authoriser__(func: Callable):
@wraps(func)
def __authoriser__(*args, **kwargs):
- if hasattr(g, "user_id") and g.user_id:
+ if hasattr(g, "user") and g.user:
with db.connection(app.config["AUTH_DB"]) as conn:
user_privileges = tuple(
priv.privilege_name for priv in
- auth_privs.user_privileges(conn, g.user_id))
+ auth_privs.user_privileges(conn, g.user))
not_assigned = [
priv for priv in privileges if priv not in user_privileges]
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
diff --git a/gn3/auth/authorisation/resources.py b/gn3/auth/authorisation/resources.py
index d01c435..f0a4b3a 100644
--- a/gn3/auth/authorisation/resources.py
+++ b/gn3/auth/authorisation/resources.py
@@ -1,10 +1,14 @@
"""Handle the management of resources."""
-from uuid import UUID
+from uuid import UUID, uuid4
from typing import NamedTuple
from gn3.auth import db
-from .groups import Group
from .checks import authorised_p
+from .exceptions import AuthorisationError
+from .groups import Group, authenticated_user_group
+
+class MissingGroupError(AuthorisationError):
+ """Raised for any resource operation without a group."""
class ResourceCategory(NamedTuple):
"""Class representing a resource category."""
@@ -22,6 +26,18 @@ class Resource(NamedTuple):
@authorised_p(("create-resource",), error_message="Could not create resource")
def create_resource(
conn: db.DbConnection, resource_name: str,
- resource_category: ResourceCategory):
+ resource_category: ResourceCategory) -> Resource:
"""Create a resource item."""
- return tuple()
+ with db.cursor(conn) as cursor:
+ group = authenticated_user_group(conn).maybe(False, lambda val: val)
+ if not group:
+ raise MissingGroupError(
+ "User with no group cannot create a resource.")
+ resource = Resource(group, uuid4(), resource_name, resource_category)
+ cursor.execute(
+ ("INSERT INTO resources VALUES (?, ?, ?, ?)"),
+ (str(resource.group.group_id), str(resource.resource_id),
+ resource_name,
+ str(resource.resource_category.resource_category_id)))
+
+ return resource
diff --git a/tests/unit/auth/conftest.py b/tests/unit/auth/conftest.py
index 37d78a3..e582640 100644
--- a/tests/unit/auth/conftest.py
+++ b/tests/unit/auth/conftest.py
@@ -65,29 +65,30 @@ def test_group(conn_after_auth_migrations):# pylint: disable=[redefined-outer-na
yield (conn_after_auth_migrations, Group(group_id, group_name))
+TEST_USERS = (
+ User(uuid.UUID("ecb52977-3004-469e-9428-2a1856725c7f"), "group@lead.er",
+ "Group Leader"),
+ User(uuid.UUID("21351b66-8aad-475b-84ac-53ce528451e3"),
+ "group@mem.ber01", "Group Member 01"),
+ User(uuid.UUID("ae9c6245-0966-41a5-9a5e-20885a96bea7"),
+ "group@mem.ber02", "Group Member 02"),
+ User(uuid.UUID("9a0c7ce5-2f40-4e78-979e-bf3527a59579"),
+ "unaff@iliated.user", "Unaffiliated User"))
+
@pytest.fixture(scope="function")
def test_users(conn_after_auth_migrations):# pylint: disable=[redefined-outer-name]
"""Fixture: setup test users."""
query = "INSERT INTO users(user_id, email, name) VALUES (?, ?, ?)"
query_user_roles = "INSERT INTO user_roles(user_id, role_id) VALUES (?, ?)"
- the_users = (
- ("ecb52977-3004-469e-9428-2a1856725c7f", "group@lead.er",
- "Group Leader"),
- ("21351b66-8aad-475b-84ac-53ce528451e3", "group@mem.ber01",
- "Group Member 01"),
- ("ae9c6245-0966-41a5-9a5e-20885a96bea7", "group@mem.ber02",
- "Group Member 02"),
- ("9a0c7ce5-2f40-4e78-979e-bf3527a59579", "unaff@iliated.user",
- "Unaffiliated User"))
test_user_roles = (
("ecb52977-3004-469e-9428-2a1856725c7f",
"a0e67630-d502-4b9f-b23f-6805d0f30e30"),)
with db.cursor(conn_after_auth_migrations) as cursor:
- cursor.executemany(query, the_users)
+ cursor.executemany(query, (
+ (str(user.user_id), user.email, user.name) for user in TEST_USERS))
cursor.executemany(query_user_roles, test_user_roles)
- yield (conn_after_auth_migrations, tuple(
- User(uuid.UUID(uid), email, name) for uid, email, name in the_users))
+ yield (conn_after_auth_migrations, TEST_USERS)
with db.cursor(conn_after_auth_migrations) as cursor:
cursor.executemany(
diff --git a/tests/unit/auth/test_resources.py b/tests/unit/auth/test_resources.py
index 04d0017..aaf22e6 100644
--- a/tests/unit/auth/test_resources.py
+++ b/tests/unit/auth/test_resources.py
@@ -7,6 +7,8 @@ from gn3.auth.authorisation.groups import Group
from gn3.auth.authorisation.resources import (
Resource, create_resource, ResourceCategory)
+from tests.unit.auth import conftest
+
group = Group(uuid.UUID("9988c21d-f02f-4d45-8966-22c968ac2fbf"), "TheTestGroup")
resource_category = ResourceCategory(
uuid.UUID("fad071a3-2fc8-40b8-992b-cdefe7dcac79"), "mrna", "mRNA Dataset")
@@ -14,20 +16,24 @@ create_resource_failure = {
"status": "error",
"message": "Unauthorised: Could not create resource"
}
+uuid_fn = lambda : uuid.UUID("d32611e3-07fc-4564-b56c-786c6db6de2b")
@pytest.mark.unit_test
@pytest.mark.parametrize(
- "user_id,expected", (
- ("ecb52977-3004-469e-9428-2a1856725c7f", Resource(
- group, uuid.UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"),
- "test_resource", resource_category)),
- ("21351b66-8aad-475b-84ac-53ce528451e3", create_resource_failure),
- ("ae9c6245-0966-41a5-9a5e-20885a96bea7", create_resource_failure),
- ("9a0c7ce5-2f40-4e78-979e-bf3527a59579", create_resource_failure),
- ("e614247d-84d2-491d-a048-f80b578216cb", create_resource_failure)))
-def test_create_resource(test_app, test_users_in_group, user_id, expected):
+ "user,expected",
+ tuple(zip(
+ conftest.TEST_USERS,
+ (Resource(
+ group, uuid.UUID("d32611e3-07fc-4564-b56c-786c6db6de2b"),
+ "test_resource", resource_category),
+ create_resource_failure,
+ create_resource_failure,
+ create_resource_failure,
+ create_resource_failure))))
+def test_create_resource(mocker, test_app, test_users_in_group, user, expected):
"""Test that resource creation works as expected."""
+ mocker.patch("gn3.auth.authorisation.resources.uuid4", uuid_fn)
conn, _group, _users = test_users_in_group
with test_app.app_context() as flask_context:
- flask_context.g.user_id = uuid.UUID(user_id)
+ flask_context.g.user = user
assert create_resource(conn, "test_resource", resource_category) == expected