aboutsummaryrefslogtreecommitdiff
path: root/gn3/auth/authorisation/users
diff options
context:
space:
mode:
Diffstat (limited to 'gn3/auth/authorisation/users')
-rw-r--r--gn3/auth/authorisation/users/collections.py30
-rw-r--r--gn3/auth/authorisation/users/views.py16
2 files changed, 45 insertions, 1 deletions
diff --git a/gn3/auth/authorisation/users/collections.py b/gn3/auth/authorisation/users/collections.py
new file mode 100644
index 0000000..9ddc138
--- /dev/null
+++ b/gn3/auth/authorisation/users/collections.py
@@ -0,0 +1,30 @@
+"""Handle user collections."""
+import json
+
+from redis import Redis
+
+from .models import User
+
+def user_collections(rconn: Redis, user: User) -> tuple:
+ """Retrieve current user collections."""
+ return tuple(json.loads(
+ rconn.hget("collections", str(user.user_id)) or
+ "[]"))
+
+def old_user_collections(rconn: Redis, user: User) -> tuple:
+ """
+ Retrieve any old user collections and migrate them to new account.
+ """
+ collections = user_collections(rconn, user)
+ old_user_accounts = [
+ acct for acct in
+ (json.loads(usr) for usr in rconn.hgetall("users").values())
+ if acct.get("email_address", "") == user.email]
+ for account in old_user_accounts:
+ collections = collections + tuple(json.loads(
+ rconn.hget("collections", account["user_id"]) or "[]"))
+ rconn.hdel("collections", account["user_id"])
+
+ rconn.hset(
+ "collections", key=str(user.user_id), value=json.dumps(collections))
+ return collections
diff --git a/gn3/auth/authorisation/users/views.py b/gn3/auth/authorisation/users/views.py
index f343e77..0a82de3 100644
--- a/gn3/auth/authorisation/users/views.py
+++ b/gn3/auth/authorisation/users/views.py
@@ -4,6 +4,7 @@ from typing import Any
from functools import partial
import sqlite3
+from redis import Redis
from email_validator import validate_email, EmailNotValidError
from flask import request, jsonify, Response, Blueprint, current_app
@@ -11,7 +12,9 @@ from gn3.auth import db
from gn3.auth.dictify import dictify
from gn3.auth.db_utils import with_db_connection
-from ..users.models import list_users
+from .models import list_users
+from .collections import user_collections, old_user_collections
+
from ..groups.models import user_group as _user_group
from ..resources.models import user_resources as _user_resources
from ..roles.models import assign_default_roles, user_roles as _user_roles
@@ -169,3 +172,14 @@ def list_all_users() -> Response:
with require_oauth.acquire("profile group") as _the_token:
return jsonify(tuple(
dictify(user) for user in with_db_connection(list_users)))
+
+@users.route("collections/list")
+@require_oauth("profile user")
+def list_user_collections() -> Response:
+ """Retrieve the user ids"""
+ with (require_oauth.acquire("profile user") as the_token,
+ Redis.from_url(current_app.config["REDIS_URI"],
+ decode_responses=True) as redisconn):
+ return jsonify(
+ user_collections(redisconn, the_token.user) or
+ old_user_collections(redisconn, the_token.user))