"""
The views/routes for the `gn3.auth.authorisation.resources.groups` package.
"""
import uuid
import datetime
from functools import partial
from dataclasses import asdict
import sqlite3
from MySQLdb.cursors import DictCursor
from flask import jsonify, Response, Blueprint, current_app
from gn_libs import mysqldb as gn3db
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
from gn_auth.auth.authorisation.privileges import privileges_by_ids
from gn_auth.auth.errors import InvalidData, NotFoundError, AuthorisationError
from gn_auth.auth.authentication.users import User, user_by_id
from gn_auth.auth.authentication.oauth2.resource_server import require_oauth
from gn_auth.auth.authorisation.resources.checks import authorised_for_spec
from gn_auth.auth.authorisation.resources.groups.models import (resource_from_group,
remove_user_from_group)
from .data import link_data_to_group
from .models import (Group,
GroupRole,
user_group,
all_groups,
DUMMY_GROUP,
group_by_id,
group_leaders,
join_requests,
data_resources,
group_role_by_id,
GroupCreationError,
accept_reject_join_request,
add_privilege_to_group_role,
group_users as _group_users,
create_group as _create_group,
delete_group as _delete_group,
delete_privilege_from_group_role)
groups = Blueprint("groups", __name__)
@groups.route("/list", methods=["GET"])
@require_oauth("profile group")
def list_groups():
"""Return the list of groups that exist."""
_kwargs = request_json()
def __add_total_group_count__(groups_info):
return {
"groups": groups_info[0],
"total-groups": groups_info[1],
"total-filtered": groups_info[2]
}
with db.connection(current_app.config["AUTH_DB"]) as conn:
return jsonify(all_groups(
conn,
search=_kwargs.get("search"),
start=int(_kwargs.get("start", "0")),
length=int(_kwargs.get("length", "0"))
).then(
__add_total_group_count__
).maybe(
{
"groups": [],
"message": "No groups found!",
"total-groups": 0,
"total-filtered": 0
},
lambda _grpdata: _grpdata))
@groups.route("/create", methods=["POST"])
@require_oauth("profile group")
def create_group():
"""Create a new group."""
with require_oauth.acquire("profile group") as the_token:
group_name=request_json().get("group_name", "").strip()
if not bool(group_name):
raise GroupCreationError(
"Could not create the group. Invalid Group name provided was "
f"`{group_name}`")
db_uri = current_app.config["AUTH_DB"]
with db.connection(db_uri) as conn:
user = the_token.user
new_group = _create_group(
conn, group_name, user, request_json().get("group_description"))
return jsonify({
**asdict(new_group), "group_leader": asdict(user)
})
@groups.route("/members/<uuid:group_id>", methods=["GET"])
@require_oauth("profile group")
def group_members(group_id: uuid.UUID) -> Response:
"""Retrieve all the members of a group."""
with require_oauth.acquire("profile group") as the_token:# pylint: disable=[unused-variable]
db_uri = current_app.config["AUTH_DB"]
## Check that user has appropriate privileges and remove the pylint disable above
with db.connection(db_uri) as conn:
return jsonify(tuple(
asdict(user) for user in _group_users(conn, group_id)))
@groups.route("/requests/join/<uuid:group_id>", methods=["POST"])
@require_oauth("profile group")
def request_to_join(group_id: uuid.UUID) -> Response:
"""Request to join a group."""
def __request__(conn: db.DbConnection, user: User, group_id: uuid.UUID,
message: str):
with db.cursor(conn) as cursor:
group = user_group(conn, user).maybe(# type: ignore[misc]
False, lambda grp: grp)# type: ignore[arg-type]
if group:
error = AuthorisationError(
"You cannot request to join a new group while being a "
"member of an existing group.")
error.error_code = 400
raise error
request_id = uuid.uuid4()
cursor.execute(
"INSERT INTO group_join_requests VALUES "
"(:request_id, :group_id, :user_id, :ts, :status, :msg)",
{
"request_id": str(request_id),
"group_id": str(group_id),
"user_id": str(user.user_id),
"ts": datetime.datetime.now().timestamp(),
"status": "PENDING",
"msg": message
})
return {
"request_id": request_id,
"message": "Successfully sent the join request."
}
with require_oauth.acquire("profile group") as the_token:
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.")))
return jsonify(results)
@groups.route("/requests/join/list", methods=["GET"])
@require_oauth("profile group")
def list_join_requests() -> Response:
"""List the pending join requests."""
with require_oauth.acquire("profile group") as the_token:
return jsonify(with_db_connection(partial(
join_requests, user=the_token.user)))
@groups.route("/requests/join/accept", methods=["POST"])
@require_oauth("profile group")
def accept_join_requests() -> Response:
"""Accept a join request."""
with require_oauth.acquire("profile group") as the_token:
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,
user=the_token.user, status="ACCEPTED")))
@groups.route("/requests/join/reject", methods=["POST"])
@require_oauth("profile group")
def reject_join_requests() -> Response:
"""Reject a join request."""
with require_oauth.acquire("profile group") as the_token:
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,
user=the_token.user, status="REJECTED")))
def unlinked_mrna_data(
conn: db.DbConnection, group: Group) -> tuple[dict, ...]:
"""
Retrieve all mRNA Assay data linked to a group but not linked to any
resource.
"""
query = (
"SELECT lmd.* FROM linked_mrna_data lmd "
"LEFT JOIN mrna_resources mr ON lmd.data_link_id=mr.data_link_id "
"WHERE lmd.group_id=? AND mr.data_link_id IS NULL")
with db.cursor(conn) as cursor:
cursor.execute(query, (str(group.group_id),))
return tuple(dict(row) for row in cursor.fetchall())
def unlinked_genotype_data(
conn: db.DbConnection, group: Group) -> tuple[dict, ...]:
"""
Retrieve all genotype data linked to a group but not linked to any resource.
"""
query = (
"SELECT lgd.* FROM linked_genotype_data lgd "
"LEFT JOIN genotype_resources gr ON lgd.data_link_id=gr.data_link_id "
"WHERE lgd.group_id=? AND gr.data_link_id IS NULL")
with db.cursor(conn) as cursor:
cursor.execute(query, (str(group.group_id),))
return tuple(dict(row) for row in cursor.fetchall())
def unlinked_phenotype_data(
authconn: db.DbConnection, gn3conn: gn3db.Connection,
group: Group) -> tuple[dict, ...]:
"""
Retrieve all phenotype data linked to a group but not linked to any
resource.
"""
with db.cursor(authconn) as authcur, gn3conn.cursor(DictCursor) as gn3cur:
authcur.execute(
"SELECT lpd.* FROM linked_phenotype_data AS lpd "
"LEFT JOIN phenotype_resources AS pr "
"ON lpd.data_link_id=pr.data_link_id "
"WHERE lpd.group_id=? AND pr.data_link_id IS NULL",
(str(group.group_id),))
results = authcur.fetchall()
ids: dict[tuple[str, ...], str] = {
(
row["SpeciesId"], row["InbredSetId"], row["PublishFreezeId"],
row["PublishXRefId"]): row["data_link_id"]
for row in results
}
if len(ids.keys()) < 1:
return tuple()
paramstr = ", ".join(["(%s, %s, %s, %s)"] * len(ids.keys()))
gn3cur.execute(
"SELECT spc.SpeciesId, spc.SpeciesName, iset.InbredSetId, "
"iset.InbredSetName, pf.Id AS PublishFreezeId, "
"pf.Name AS dataset_name, pf.FullName AS dataset_fullname, "
"pf.ShortName AS dataset_shortname, pxr.Id AS PublishXRefId, "
"pub.PubMed_ID, pub.Title, pub.Year, "
"phen.Pre_publication_description, "
"phen.Post_publication_description, phen.Original_description "
"FROM "
"Species AS spc "
"INNER JOIN InbredSet AS iset "
"ON spc.SpeciesId=iset.SpeciesId "
"INNER JOIN PublishFreeze AS pf "
"ON iset.InbredSetId=pf.InbredSetId "
"INNER JOIN PublishXRef AS pxr "
"ON pf.InbredSetId=pxr.InbredSetId "
"INNER JOIN Publication AS pub "
"ON pxr.PublicationId=pub.Id "
"INNER JOIN Phenotype AS phen "
"ON pxr.PhenotypeId=phen.Id "
"WHERE (spc.SpeciesId, iset.InbredSetId, pf.Id, pxr.Id) "
f"IN ({paramstr})",
tuple(item for sublist in ids.keys() for item in sublist))
return tuple({
**{key: value for key, value in row.items() if key not in
("Post_publication_description", "Pre_publication_description",
"Original_description")},
"description": (
row["Post_publication_description"] or
row["Pre_publication_description"] or
row["Original_description"]),
"data_link_id": ids[tuple(str(row[key]) for key in (
"SpeciesId", "InbredSetId", "PublishFreezeId",
"PublishXRefId"))]
} for row in gn3cur.fetchall())
@groups.route("/<string:resource_type>/unlinked-data")
@require_oauth("profile group resource")
def unlinked_data(resource_type: str) -> Response:
"""View data linked to the group but not linked to any resource."""
if resource_type in ("system", "group"):
return jsonify(tuple())
if resource_type not in ("all", "mrna", "genotype", "phenotype", "inbredset-group"):
raise AuthorisationError(f"Invalid resource type {resource_type}")
with require_oauth.acquire("profile group resource") as the_token:
db_uri = current_app.config["AUTH_DB"]
gn3db_uri = current_app.config["SQL_URI"]
with (db.connection(db_uri) as authconn,
gn3db.database_connection(gn3db_uri) as gn3conn):
ugroup = user_group(authconn, the_token.user).maybe(# type: ignore[misc]
DUMMY_GROUP, lambda grp: grp)
if ugroup == DUMMY_GROUP:
return jsonify(tuple())
unlinked_fns = {
"mrna": unlinked_mrna_data,
"genotype": unlinked_genotype_data,
"phenotype": lambda conn, grp: partial(
unlinked_phenotype_data, gn3conn=gn3conn)(
authconn=conn, group=grp),
"inbredset-group": lambda authconn, ugroup: [] # Still need to implement this
}
return jsonify(tuple(
dict(row) for row in unlinked_fns[resource_type](
authconn, ugroup)))
return jsonify(tuple())
@groups.route("/data/link", methods=["POST"])
@require_oauth("profile group resource")
def link_data() -> Response:
"""Link selected data to specified group."""
with require_oauth.acquire("profile group resource") as _the_token:
form = request_json()
group_id = uuid.UUID(form["group_id"])
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!")
def __link__(conn: db.DbConnection):
group = group_by_id(conn, group_id)
with gn3db.database_connection(current_app.config["SQL_URI"]) as gn3conn:
return link_data_to_group(
conn, gn3conn, dataset_type, dataset_ids, group)
return jsonify(with_db_connection(__link__))
@groups.route("/role/<uuid:group_role_id>", methods=["GET"])
@require_oauth("profile group")
def view_group_role(group_role_id: uuid.UUID):
"""Return the details of the given role."""
with require_oauth.acquire("profile group role") as the_token:
def __group_role__(conn: db.DbConnection) -> GroupRole:
group = user_group(conn, the_token.user).maybe(#type: ignore[misc]
DUMMY_GROUP, lambda grp: grp)
if group == DUMMY_GROUP:
raise AuthorisationError(
"A user without a group cannot view group roles.")
return group_role_by_id(conn, group, group_role_id)
return jsonify(asdict(with_db_connection(__group_role__)))
def __add_remove_priv_to_from_role__(conn: db.DbConnection,
group_role_id: uuid.UUID,
direction: str,
user: User) -> GroupRole:
assert direction in ("ADD", "DELETE")
group = user_group(conn, user).maybe(# type: ignore[misc]
DUMMY_GROUP, lambda grp: grp)
if group == DUMMY_GROUP:
raise AuthorisationError(
"You need to be a member of a group to edit roles.")
try:
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:
raise NotFoundError("Privilege not found.")
dir_fns = {
"ADD": add_privilege_to_group_role,
"DELETE": delete_privilege_from_group_role
}
return dir_fns[direction](
conn,
group_role_by_id(conn, group, group_role_id),
privileges[0])
except AssertionError as aerr:
raise InvalidData(aerr.args[0]) from aerr
@groups.route("/role/<uuid:group_role_id>/privilege/add", methods=["POST"])
@require_oauth("profile group")
def add_priv_to_role(group_role_id: uuid.UUID) -> Response:
"""Add privilege to group role."""
with require_oauth.acquire("profile group role") as the_token:
return jsonify({
**asdict(with_db_connection(partial(
__add_remove_priv_to_from_role__, group_role_id=group_role_id,
direction="ADD", user=the_token.user))),
"description": "Privilege added successfully"
})
@groups.route("/role/<uuid:group_role_id>/privilege/delete", methods=["POST"])
@require_oauth("profile group")
def delete_priv_from_role(group_role_id: uuid.UUID) -> Response:
"""Delete privilege from group role."""
with require_oauth.acquire("profile group role") as the_token:
return jsonify({
**asdict(with_db_connection(partial(
__add_remove_priv_to_from_role__, group_role_id=group_role_id,
direction="DELETE", user=the_token.user))),
"description": "Privilege deleted successfully"
})
@groups.route("/<uuid:group_id>", methods=["GET"])
@require_oauth("profile group")
def view_group(group_id: uuid.UUID) -> Response:
"""View a particular group's details."""
# TODO: do authorisation checks here…
with (require_oauth.acquire("profile group") as _token,
db.connection(current_app.config["AUTH_DB"]) as conn):
return jsonify(group_by_id(conn, group_id))
@groups.route("/<uuid:group_id>/data-resources", methods=["GET"])
@require_oauth("profile group")
def view_group_data_resources(group_id: uuid.UUID) -> Response:
"""View data resources linked to the group."""
# TODO: do authorisation checks here…
with (require_oauth.acquire("profile group") as _token,
db.connection(current_app.config["AUTH_DB"]) as conn):
return jsonify(tuple(data_resources(conn, group_id)))
@groups.route("/<uuid:group_id>/leaders", methods=["GET"])
@require_oauth("profile group")
def view_group_leaders(group_id: uuid.UUID) -> Response:
"""View a group's leaders."""
# TODO: do authorisation checks here…
with (require_oauth.acquire("profile group") as _token,
db.connection(current_app.config["AUTH_DB"]) as conn):
return jsonify(tuple(group_leaders(conn, group_id)))
@groups.route("/<uuid:group_id>/remove-member", methods=["POST"])
@require_oauth("profile group")
def remove_group_member(group_id: uuid.UUID):
"""Remove a user as member of this group."""
with (require_oauth.acquire("profile group") as _token,
db.connection(current_app.config["AUTH_DB"]) as conn):
group = group_by_id(conn, group_id)
grp_resource = resource_from_group(conn, group)
if not authorised_for_spec(
conn,
_token.user.user_id,
grp_resource.resource_id,
"(OR group:user:remove-group-member system:group:remove-group-member)"):
raise AuthorisationError(
"You do not have appropriate privileges to remove a user from this "
"group.")
form = request_json()
if not bool(form.get("user_id")):
response = jsonify({
"error": "MissingUserId",
"error-description": (
"Expected 'user_id' value/parameter was not provided.")
})
response.status_code = 400
return response
try:
user = user_by_id(conn, uuid.UUID(form["user_id"]))
remove_user_from_group(conn, group, user, grp_resource)
success_msg = (
f"User '{user.name} ({user.email})' is no longer a member of "
f"group '{group.group_name}'.\n"
"They could, however, still have access to resources owned by "
"the group.")
return jsonify({
"description": success_msg,
"message": success_msg
})
except ValueError as _verr:
response = jsonify({
"error": "InvalidUserId",
"error-description": "The 'user_id' provided was invalid"
})
response.status_code = 400
return response
@groups.route("/<uuid:group_id>/delete", methods=["DELETE"])
@require_oauth("profile group")
def delete_group(group_id: uuid.UUID) -> Response:
"""Delete group with the specified `group_id`."""
with (require_oauth.acquire("profile group") as _token,
db.connection(current_app.config["AUTH_DB"]) as conn):
group = group_by_id(conn, group_id)
grp_resource = resource_from_group(conn, group)
if not authorised_for_spec(
conn,
_token.user.user_id,
grp_resource.resource_id,
"(AND system:group:delete-group)"):
raise AuthorisationError(
"You do not have appropriate privileges to delete this group.")
try:
_delete_group(conn, group.group_id)
return Response(status=204)
except sqlite3.IntegrityError as _s3ie:
response = jsonify({
"error": "IntegrityError",
"error-description": (
"A group that has members, linked resources, or both, "
"cannot be deleted from the system. Remove any members and "
"unlink any linked resources, and try again.")
})
response.status_code = 400
return response