aboutsummaryrefslogtreecommitdiff
path: root/gn2/wqflask/oauth2/resources.py
blob: 32efbd2aa98ed98332340c5f596709e7f52a6787 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import uuid

from flask import (
    flash, request, url_for, redirect, Response, Blueprint)

from . import client
from .ui import render_ui
from .checks import require_oauth2
from .client import oauth2_get, oauth2_post
from .request_utils import (
    flash_error, flash_success, request_error, process_error)

resources = Blueprint("resource", __name__)

@resources.route("/", methods=["GET"])
@require_oauth2
def user_resources():
    """List the resources the user has access to."""
    def __success__(resources):
        return render_ui("oauth2/resources.html", resources=resources)

    return oauth2_get("auth/user/resources").either(
        request_error, __success__)

@resources.route("/create", methods=["GET", "POST"])
@require_oauth2
def create_resource():
    """Create a new resource."""
    def __render_template__(categories=[], error=None):
        return render_ui(
            "oauth2/create-resource.html",
            resource_categories=categories,
            resource_category_error=error,
            resource_name=request.args.get("resource_name"),
            resource_category=request.args.get("resource_category"))

    if request.method == "GET":
        return oauth2_get("auth/resource/categories").either(
            lambda error: __render_template__(error=process_error(
                error, "Could not retrieve resource categories")),
            lambda cats: __render_template__(categories=cats))

    def __perr__(error):
        err = process_error(error)
        flash(f"{err['error']}: {err['error_description']}", "alert-danger")
        return redirect(url_for(
            "oauth2.resource.create_resource",
            resource_name=request.form.get("resource_name"),
            resource_category=request.form.get("resource_category")))
    def __psuc__(succ):
        flash("Resource created successfully", "alert-success")
        return redirect(url_for("oauth2.resource.user_resources"))
    return oauth2_post(
        "auth/resource/create", data=request.form).either(
            __perr__, __psuc__)

def __compute_page__(submit, current_page):
    if submit == "next":
        return current_page + 1
    return (current_page - 1) or 1

@resources.route("/view/<uuid:resource_id>", methods=["GET"])
@require_oauth2
def view_resource(resource_id: uuid.UUID):
    """View the given resource."""
    page = __compute_page__(request.args.get("submit"),
                            int(request.args.get("page", "1"), base=10))
    count_per_page = int(request.args.get("count_per_page", "100"), base=10)
    def __users_success__(
            resource, unlinked_data, users_n_roles, this_user, group_roles,
            users):
        return render_ui(
            "oauth2/view-resource.html", resource=resource,
            unlinked_data=unlinked_data, users_n_roles=users_n_roles,
            this_user=this_user, group_roles=group_roles, users=users,
            page=page, count_per_page=count_per_page)

    def __group_roles_success__(
            resource, unlinked_data, users_n_roles, this_user, group_roles):
        return oauth2_get("auth/user/list").either(
            lambda err: render_ui(
                "oauth2/view-resource.html", resource=resource,
                unlinked_data=unlinked_data, users_n_roles=users_n_roles,
                this_user=this_user, group_roles=group_roles,
                users_error=process_error(err), count_per_page=count_per_page),
            lambda users: __users_success__(
                resource, unlinked_data, users_n_roles, this_user, group_roles,
                users))

    def __this_user_success__(resource, unlinked_data, users_n_roles, this_user):
        return oauth2_get("auth/group/roles").either(
            lambda err: render_ui(
                "oauth2/view-resources.html", resource=resource,
                unlinked_data=unlinked_data, users_n_roles=users_n_roles,
                this_user=this_user, group_roles_error=process_error(err)),
            lambda groles: __group_roles_success__(
                resource, unlinked_data, users_n_roles, this_user, groles))

    def __users_n_roles_success__(resource, unlinked_data, users_n_roles):
        return oauth2_get("auth/user/").either(
            lambda err: render_ui(
                "oauth2/view-resources.html",
                this_user_error=process_error(err)),
            lambda usr_dets: __this_user_success__(
                resource, unlinked_data, users_n_roles, usr_dets))

    def __unlinked_success__(resource, unlinked_data):
        return oauth2_get(f"auth/resource/{resource_id}/user/list").either(
            lambda err: render_ui(
                "oauth2/view-resource.html",
                resource=resource,
                unlinked_data=unlinked_data,
                users_n_roles_error=process_error(err),
                page=page,
                count_per_page=count_per_page),
            lambda users_n_roles: __users_n_roles_success__(
                resource, unlinked_data, users_n_roles))

    def __resource_success__(resource):
        dataset_type = resource["resource_category"]["resource_category_key"]
        return oauth2_get(f"auth/group/{dataset_type}/unlinked-data").either(
            lambda err: render_ui(
                "oauth2/view-resource.html", resource=resource,
                unlinked_error=process_error(err)),
            lambda unlinked: __unlinked_success__(resource, unlinked))

    def __fetch_resource_data__(resource):
        """Fetch the resource's data."""
        return client.get(
            f"auth/resource/view/{resource['resource_id']}/data?page={page}"
            f"&count_per_page={count_per_page}").either(
                lambda err: {
                    **resource, "resource_data_error": process_error(err)
                },
                lambda resdata: {**resource, "resource_data": resdata})

    return oauth2_get(f"auth/resource/view/{resource_id}").map(
        __fetch_resource_data__).either(
            lambda err: render_ui(
                "oauth2/view-resource.html",
                resource=None, resource_error=process_error(err)),
            __resource_success__)

@resources.route("/data/link", methods=["POST"])
@require_oauth2
def link_data_to_resource():
    """Link group data to a resource"""
    form = request.form
    try:
        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"
        assert form["dataset_type"].lower() in (
            "mrna", "genotype", "phenotype"), "Invalid dataset type provided."
        resource_id = form["resource_id"]

        def __error__(error):
            err = process_error(error)
            flash(f"{err['error']}: {err['error_description']}", "alert-danger")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))

        def __success__(success):
            flash(f"Data linked to resource successfully", "alert-success")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))
        return oauth2_post("auth/resource/data/link", data=dict(form)).either(
            __error__,
            __success__)
    except AssertionError as aserr:
        flash(aserr.args[0], "alert-danger")
        return redirect(url_for(
            "oauth2.resource.view_resource", resource_id=form["resource_id"]))

@resources.route("/data/unlink", methods=["POST"])
@require_oauth2
def unlink_data_from_resource():
    """Unlink group data from a resource"""
    form = request.form
    try:
        assert "resource_id" in form, "Resource ID not provided."
        assert "data_link_id" in form, "Data Link ID not provided."
        resource_id = form["resource_id"]

        def __error__(error):
            err = process_error(error)
            flash(f"{err['error']}: {err['error_description']}", "alert-danger")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))

        def __success__(success):
            flash(f"Data unlinked from resource successfully", "alert-success")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))
        return oauth2_post(
            "auth/resource/data/unlink", data=dict(form)).either(
            __error__, __success__)
    except AssertionError as aserr:
        flash(aserr.args[0], "alert-danger")
        return redirect(url_for(
            "oauth2.resource.view_resource", resource_id=form["resource_id"]))

@resources.route("<uuid:resource_id>/user/assign", methods=["POST"])
@require_oauth2
def assign_role(resource_id: uuid.UUID) -> Response:
    form = request.form
    group_role_id = form.get("group_role_id", "")
    user_email = form.get("user_email", "")
    try:
        assert bool(group_role_id), "The role must be provided."
        assert bool(user_email), "The user email must be provided."

        def __assign_error__(error):
            err = process_error(error)
            flash(f"{err['error']}: {err['error_description']}", "alert-danger")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))

        def __assign_success__(success):
            flash(success["description"], "alert-success")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))

        return oauth2_post(
            f"auth/resource/{resource_id}/user/assign",
            data={
                "group_role_id": group_role_id,
                "user_email": user_email
            }).either(__assign_error__, __assign_success__)
    except AssertionError as aserr:
        flash(aserr.args[0], "alert-danger")
        return redirect(url_for("oauth2.resources.view_resource", resource_id=resource_id))

@resources.route("<uuid:resource_id>/user/unassign", methods=["POST"])
@require_oauth2
def unassign_role(resource_id: uuid.UUID) -> Response:
    form = request.form
    group_role_id = form.get("group_role_id", "")
    user_id = form.get("user_id", "")
    try:
        assert bool(group_role_id), "The role must be provided."
        assert bool(user_id), "The user id must be provided."

        def __unassign_error__(error):
            err = process_error(error)
            flash(f"{err['error']}: {err['error_description']}", "alert-danger")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))

        def __unassign_success__(success):
            flash(success["description"], "alert-success")
            return redirect(url_for(
                "oauth2.resource.view_resource", resource_id=resource_id))

        return oauth2_post(
            f"auth/resource/{resource_id}/user/unassign",
            data={
                "group_role_id": group_role_id,
                "user_id": user_id
            }).either(__unassign_error__, __unassign_success__)
    except AssertionError as aserr:
        flash(aserr.args[0], "alert-danger")
        return redirect(url_for("oauth2.resources.view_resource", resource_id=resource_id))

@resources.route("/toggle/<uuid:resource_id>", methods=["POST"])
@require_oauth2
def toggle_public(resource_id: uuid.UUID):
    """Toggle the given resource's public status."""
    def __handle_error__(err):
        flash_error(process_error(err))
        return redirect(url_for(
            "oauth2.resource.view_resource", resource_id=resource_id))

    def __handle_success__(success):
        flash_success(success)
        return redirect(url_for(
            "oauth2.resource.view_resource", resource_id=resource_id))

    return oauth2_post(
        f"auth/resource/{resource_id}/toggle-public", data={}).either(
            lambda err: __handle_error__(err),
            lambda suc: __handle_success__(suc))

@resources.route("/edit/<uuid:resource_id>", methods=["GET"])
@require_oauth2
def edit_resource(resource_id: uuid.UUID):
    """Edit the given resource."""
    return "WOULD Edit THE GIVEN RESOURCE'S DETAILS"

@resources.route("/delete/<uuid:resource_id>", methods=["GET"])
@require_oauth2
def delete_resource(resource_id: uuid.UUID):
    """Delete the given resource."""
    return "WOULD DELETE THE GIVEN RESOURCE"