aboutsummaryrefslogtreecommitdiff
path: root/gn_auth/auth
diff options
context:
space:
mode:
Diffstat (limited to 'gn_auth/auth')
-rw-r--r--gn_auth/auth/authorisation/data/views.py25
-rw-r--r--gn_auth/auth/authorisation/resources/groups/views.py23
-rw-r--r--gn_auth/auth/authorisation/resources/views.py20
-rw-r--r--gn_auth/auth/authorisation/roles/models.py2
-rw-r--r--gn_auth/auth/authorisation/users/views.py10
-rw-r--r--gn_auth/auth/requests.py6
6 files changed, 49 insertions, 37 deletions
diff --git a/gn_auth/auth/authorisation/data/views.py b/gn_auth/auth/authorisation/data/views.py
index 86dafe5..7ed69e3 100644
--- a/gn_auth/auth/authorisation/data/views.py
+++ b/gn_auth/auth/authorisation/data/views.py
@@ -14,6 +14,7 @@ from flask import request, jsonify, Response, Blueprint, current_app as app
from gn_auth import jobs
from gn_auth.commands import run_async_cmd
+from gn_auth.auth.requests import request_json
from gn_auth.auth.errors import InvalidData, NotFoundError
from gn_auth.auth.authorisation.resources.groups.models import group_by_id
@@ -184,18 +185,18 @@ def __search_mrna__():
return jsonify(with_db_connection(__ungrouped__))
def __request_key__(key: str, default: Any = ""):
- if bool(request.json):
- return request.json.get(#type: ignore[union-attr]
- key, request.args.get(key, request.json.get(key, default)))
- return request.args.get(key, request.json.get(key, default))
+ if bool(request_json()):
+ return request_json().get(#type: ignore[union-attr]
+ key, request.args.get(key, request_json().get(key, default)))
+ return request.args.get(key, request_json().get(key, default))
def __request_key_list__(key: str, default: tuple[Any, ...] = tuple()):
- if bool(request.json):
- return (request.json.get(key,[])#type: ignore[union-attr]
- or request.args.getlist(key) or request.json.getlist(key)
+ if bool(request_json()):
+ return (request_json().get(key,[])#type: ignore[union-attr]
+ or request.args.getlist(key) or request_json().get(key)
or list(default))
return (request.args.getlist(key)
- or request.json.getlist(key) or list(default))
+ or request_json().get(key) or list(default))
def __search_genotypes__():
query = __request_key__("query", "")
@@ -240,7 +241,7 @@ def __search_phenotypes__():
@require_oauth("profile group resource")
def search_unlinked_data():
"""Search for various unlinked data."""
- dataset_type = request.json["dataset_type"]
+ dataset_type = request_json()["dataset_type"]
search_fns = {
"mrna": __search_mrna__,
"genotype": __search_genotypes__,
@@ -281,7 +282,7 @@ def link_genotypes() -> Response:
return link_genotype_data(conn, group_by_id(conn, group_id), datasets)
return jsonify(with_db_connection(
- partial(__link__, **__values__(request.json))))
+ partial(__link__, **__values__(request_json()))))
@data.route("/link/mrna", methods=["POST"])
def link_mrna() -> Response:
@@ -306,7 +307,7 @@ def link_mrna() -> Response:
return link_mrna_data(conn, group_by_id(conn, group_id), datasets)
return jsonify(with_db_connection(
- partial(__link__, **__values__(request.json))))
+ partial(__link__, **__values__(request_json()))))
@data.route("/link/phenotype", methods=["POST"])
def link_phenotype() -> Response:
@@ -334,4 +335,4 @@ def link_phenotype() -> Response:
conn, gn3conn, group_by_id(conn, group_id), traits)
return jsonify(with_db_connection(
- partial(__link__, **__values__(request.json))))
+ partial(__link__, **__values__(request_json()))))
diff --git a/gn_auth/auth/authorisation/resources/groups/views.py b/gn_auth/auth/authorisation/resources/groups/views.py
index 47bf047..401be00 100644
--- a/gn_auth/auth/authorisation/resources/groups/views.py
+++ b/gn_auth/auth/authorisation/resources/groups/views.py
@@ -7,13 +7,14 @@ from functools import partial
from dataclasses import asdict
from MySQLdb.cursors import DictCursor
-from flask import request, jsonify, Response, Blueprint, current_app
+from flask import jsonify, Response, Blueprint, current_app
+
+from gn_auth.auth.requests import request_json
from gn_auth.auth.db import sqlite3 as db
from gn_auth.auth.db import mariadb as gn3db
from gn_auth.auth.db.sqlite3 import with_db_connection
-from gn_auth.auth.authorisation.checks import authorised_p
from gn_auth.auth.authorisation.privileges import privileges_by_ids
from gn_auth.auth.errors import InvalidData, NotFoundError, AuthorisationError
@@ -26,7 +27,7 @@ from .models import (
join_requests, group_role_by_id, GroupCreationError,
accept_reject_join_request, group_users as _group_users,
create_group as _create_group, add_privilege_to_group_role,
- delete_privilege_from_group_role, create_group_role as _create_group_role)
+ delete_privilege_from_group_role)
groups = Blueprint("groups", __name__)
@@ -45,7 +46,7 @@ def list_groups():
def create_group():
"""Create a new group."""
with require_oauth.acquire("profile group") as the_token:
- group_name=request.json.get("group_name", "").strip()
+ group_name=request_json().get("group_name", "").strip()
if not bool(group_name):
raise GroupCreationError("Could not create the group.")
@@ -53,7 +54,7 @@ def create_group():
with db.connection(db_uri) as conn:
user = the_token.user
new_group = _create_group(
- conn, group_name, user, request.json.get("group_description"))
+ conn, group_name, user, request_json().get("group_description"))
return jsonify({
**asdict(new_group), "group_leader": asdict(user)
})
@@ -102,7 +103,7 @@ def request_to_join(group_id: uuid.UUID) -> Response:
}
with require_oauth.acquire("profile group") as the_token:
- form = request.json
+ form = request_json()
results = with_db_connection(partial(
__request__, user=the_token.user, group_id=group_id, message=form.get(
"message", "I hereby request that you add me to your group.")))
@@ -121,7 +122,7 @@ def list_join_requests() -> Response:
def accept_join_requests() -> Response:
"""Accept a join request."""
with require_oauth.acquire("profile group") as the_token:
- form = request.json
+ form = request_json()
request_id = uuid.UUID(form.get("request_id"))
return jsonify(with_db_connection(partial(
accept_reject_join_request, request_id=request_id,
@@ -132,7 +133,7 @@ def accept_join_requests() -> Response:
def reject_join_requests() -> Response:
"""Reject a join request."""
with require_oauth.acquire("profile group") as the_token:
- form = request.json
+ form = request_json()
request_id = uuid.UUID(form.get("request_id"))
return jsonify(with_db_connection(partial(
accept_reject_join_request, request_id=request_id,
@@ -263,9 +264,9 @@ def unlinked_data(resource_type: str) -> Response:
def link_data() -> Response:
"""Link selected data to specified group."""
with require_oauth.acquire("profile group resource") as _the_token:
- form = request.json
+ form = request_json()
group_id = uuid.UUID(form["group_id"])
- dataset_ids = form.getlist("dataset_ids")
+ dataset_ids = form.get("dataset_ids")
dataset_type = form.get("dataset_type")
if dataset_type not in ("mrna", "genotype", "phenotype"):
raise InvalidData("Unexpected dataset type requested!")
@@ -305,7 +306,7 @@ def __add_remove_priv_to_from_role__(conn: db.DbConnection,
raise AuthorisationError(
"You need to be a member of a group to edit roles.")
try:
- privilege_id = request.json.get("privilege_id", "")
+ privilege_id = request_json().get("privilege_id", "")
assert bool(privilege_id), "Privilege to add must be provided."
privileges = privileges_by_ids(conn, (privilege_id,))
if len(privileges) == 0:
diff --git a/gn_auth/auth/authorisation/resources/views.py b/gn_auth/auth/authorisation/resources/views.py
index 0e07ffa..5c2b66e 100644
--- a/gn_auth/auth/authorisation/resources/views.py
+++ b/gn_auth/auth/authorisation/resources/views.py
@@ -14,6 +14,8 @@ from authlib.integrations.flask_oauth2.errors import _HTTPException
from flask import (make_response, request, jsonify, Response,
Blueprint, current_app as app)
+from gn_auth.auth.requests import request_json
+
from gn_auth.auth.db import sqlite3 as db
from gn_auth.auth.db.sqlite3 import with_db_connection
@@ -61,7 +63,7 @@ def list_resource_categories() -> Response:
def create_resource() -> Response:
"""Create a new resource"""
with require_oauth.acquire("profile group resource") as the_token:
- form = request.json
+ form = request_json()
resource_name = form.get("resource_name")
resource_category_id = UUID(form.get("resource_category"))
db_uri = app.config["AUTH_DB"]
@@ -134,7 +136,7 @@ def view_resource_data(resource_id: UUID) -> Response:
def link_data():
"""Link group data to a specific resource."""
try:
- form = request.json
+ form = request_json()
assert "resource_id" in form, "Resource ID not provided."
assert "data_link_id" in form, "Data Link ID not provided."
assert "dataset_type" in form, "Dataset type not specified"
@@ -158,7 +160,7 @@ def link_data():
def unlink_data():
"""Unlink data bound to a specific resource."""
try:
- form = request.json
+ form = request_json()
assert "resource_id" in form, "Resource ID not provided."
assert "data_link_id" in form, "Data Link ID not provided."
@@ -247,7 +249,7 @@ def assign_role_to_user(resource_id: UUID) -> Response:
"""Assign a role on the specified resource to a user."""
with require_oauth.acquire("profile group resource role") as the_token:
try:
- form = request.json
+ form = request_json()
group_role_id = form.get("group_role_id", "")
user_email = form.get("user_email", "")
assert bool(group_role_id), "The role must be provided."
@@ -272,7 +274,7 @@ def unassign_role_to_user(resource_id: UUID) -> Response:
"""Unassign a role on the specified resource from a user."""
with require_oauth.acquire("profile group resource role") as the_token:
try:
- form = request.json
+ form = request_json()
group_role_id = form.get("group_role_id", "")
user_id = form.get("user_id", "")
assert bool(group_role_id), "The role must be provided."
@@ -399,7 +401,7 @@ def resource_roles(resource_id: UUID) -> Response:
def resources_authorisation():
"""Get user authorisations for given resource(s):"""
try:
- data = request.json
+ data = request_json()
assert (data and "resource-ids" in data)
resource_ids = tuple(UUID(resid) for resid in data["resource-ids"])
pubres = tuple(
@@ -546,7 +548,7 @@ def unassign_resource_role_privilege(resource_id: UUID, role_id: UUID):
"You are not authorised to edit/update this role.")
# Actually unassign the privilege from the role
- privilege_id = request.json.get("privilege_id")
+ privilege_id = request_json().get("privilege_id")
if not privilege_id:
raise AuthorisationError(
"You need to provide a privilege to unassign")
@@ -583,7 +585,7 @@ def resource_role_users(resource_id: UUID, role_id: UUID):
@require_oauth("profile group resource")
def create_resource_role(resource_id: UUID):
"""Create a role to act upon a specific resource."""
- role_name = request.json.get("role_name", "").strip()
+ role_name = request_json().get("role_name", "").strip()
if not bool(role_name):
raise BadRequest("You must provide the name for the new role.")
@@ -594,7 +596,7 @@ def create_resource_role(resource_id: UUID):
if not bool(resource):
raise BadRequest("No resource with that ID exists.")
- privileges = privileges_by_ids(conn, request.json.get("privileges", []))
+ privileges = privileges_by_ids(conn, request_json().get("privileges", []))
if len(privileges) == 0:
raise BadRequest(
"You must provide at least one privilege for the new role.")
diff --git a/gn_auth/auth/authorisation/roles/models.py b/gn_auth/auth/authorisation/roles/models.py
index 03f88d7..dc1dfdc 100644
--- a/gn_auth/auth/authorisation/roles/models.py
+++ b/gn_auth/auth/authorisation/roles/models.py
@@ -137,7 +137,7 @@ def user_resource_roles(
conn: db.DbConnection,
user: User,
resource: Resource
-) -> tuple[Role]:
+) -> tuple[Role, ...]:
"""Retrieve all roles assigned to a user for a particular resource."""
with db.cursor(conn) as cursor:
cursor.execute(
diff --git a/gn_auth/auth/authorisation/users/views.py b/gn_auth/auth/authorisation/users/views.py
index cc70d76..8135ed3 100644
--- a/gn_auth/auth/authorisation/users/views.py
+++ b/gn_auth/auth/authorisation/users/views.py
@@ -22,6 +22,8 @@ from flask import (
from gn_auth.smtp import send_message, build_email_message
+from gn_auth.auth.requests import request_json
+
from gn_auth.auth.db import sqlite3 as db
from gn_auth.auth.db.sqlite3 import with_db_connection
@@ -166,7 +168,7 @@ def register_user() -> Response:
__assert_not_logged_in__(conn)
try:
- form = request.json
+ form = request_json()
email = validate_email(form.get("email", "").strip(),
check_deliverability=True)
password = validate_password(
@@ -204,7 +206,7 @@ def delete_verification_code(cursor, code: str):
@users.route("/verify", methods=["GET", "POST"])
def verify_user():
"""Verify users are not bots."""
- form = request.json
+ form = request_json()
loginuri = redirect(url_for(
"oauth2.auth.authorise",
response_type=(request.args.get("response_type")
@@ -308,7 +310,7 @@ def list_all_users() -> Response:
@users.route("/handle-unverified", methods=["POST"])
def handle_unverified():
"""Handle case where user tries to login but is unverified"""
- form = request.json
+ form = request_json()
# TODO: Maybe have a GN2_URI setting here?
# or pass the client_id here?
return render_template(
@@ -321,7 +323,7 @@ def handle_unverified():
@users.route("/send-verification", methods=["POST"])
def send_verification_code():
"""Send verification code email."""
- form = request.json
+ form = request_json()
with (db.connection(current_app.config["AUTH_DB"]) as conn,
db.cursor(conn) as cursor):
user = user_by_email(conn, form["user_email"])
diff --git a/gn_auth/auth/requests.py b/gn_auth/auth/requests.py
new file mode 100644
index 0000000..6301029
--- /dev/null
+++ b/gn_auth/auth/requests.py
@@ -0,0 +1,6 @@
+"""Utilities to deal with requests."""
+from flask import request
+
+def request_json() -> dict:
+ """Retrieve the JSON sent in a request."""
+ return request.json or {}