-
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathsources.py
More file actions
533 lines (477 loc) · 17 KB
/
sources.py
File metadata and controls
533 lines (477 loc) · 17 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import logging
from backend.auth.jwt import min_role_required
from backend.mixpanel.mix import track_to_mp
from backend.database.models.user import User, UserRole
from ..schemas import (
validate_request, paginate_results, ordered_jsonify,
NodeConflictException)
from flask import Blueprint, abort, current_app, request
from flask_jwt_extended import get_jwt
from flask_jwt_extended.view_decorators import jwt_required
from npdi_oas.sources import CreateSource, UpdateSource
from ..database import (
Source,
MemberRole,
Invitation,
StagedInvitation,
)
from ..dto import InviteUserDTO
from flask_mail import Message
from ..config import TestingConfig
bp = Blueprint("source_routes", __name__, url_prefix="/api/v1/sources")
@bp.route("/<source_uid>", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
def get_sources(source_uid: str):
"""Get a single source by UID."""
p = Source.nodes.get_or_none(uid=source_uid)
if p is None:
abort(404, description="Source not found")
return p.to_json()
@bp.route("/", methods=["POST"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate_request(CreateSource)
def create_source():
"""Create a contributing source."""
logger = logging.getLogger("create_source")
body: CreateSource = request.validated_body
jwt_decoded = get_jwt()
current_user = User.get(jwt_decoded["sub"])
if (
body.name is not None
and body.url is not None
and body.contact_email is not None
and body.name != ""
and body.url != ""
and body.contact_email != ""
):
# Creates a new instance of the Source and saves it to the DB
try:
new_p = Source.from_dict(body.model_dump())
except NodeConflictException:
abort(409, description="Source already exists")
except Exception as e:
abort(
400,
description=f"Failed to create source: {e}")
# Connects the current user to the new source as an admin
new_p.members.connect(
current_user,
{
"role": MemberRole.ADMIN.value
}
)
# update to UserRole contributor status
if (current_user.role_enum.get_value()
< UserRole.CONTRIBUTOR.get_value()):
current_user.role = UserRole.CONTRIBUTOR.value
current_user.save()
logger.info(f"User {current_user.uid} created source {new_p.name}")
track_to_mp(request, "create_source", {
"source_name": new_p.name,
"source_contact": new_p.contact_email
})
return new_p.to_json()
else:
return {
"status": "error",
"message": "Failed to create source. " +
"Please include all of the following"
}, 400
@bp.route("/", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
def get_all_sources():
"""Get all sources.
Accepts Query Parameters for pagination:
per_page: number of results per page
page: page number
"""
args = request.args
q_page = args.get("page", 1, type=int)
q_per_page = args.get("per_page", 20, type=int)
all_sources = Source.nodes.all()
results = paginate_results(all_sources, q_page, q_per_page)
return ordered_jsonify(results), 200
@bp.route("/<source_uid>", methods=["PATCH"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate_request(UpdateSource)
def update_source(source_uid: str):
"""Update a source's information."""
body: UpdateSource = request.validated_body
current_user = User.get(get_jwt()["sub"])
p = Source.nodes.get_or_none(uid=source_uid)
if p is None:
abort(404, description="Source not found")
if p.members.is_connected(current_user):
rel = p.members.relationship(current_user)
if not rel.is_administrator():
abort(403, description="Not authorized to update source")
else:
abort(403, description="Not authorized to update source")
try:
p.from_dict(body.model_dump(), source_uid)
p.refresh()
return p.to_json()
except Exception as e:
abort(400, description=str(e))
@bp.route("/<source_uid>/members/", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
def get_source_members(source_uid: int):
"""Get all members of a source.
Accepts Query Parameters for pagination:
per_page: number of results per page
page: page number
"""
args = request.args
q_page = args.get("page", 1, type=int)
q_per_page = args.get("per_page", 20, type=int)
p = Source.nodes.get_or_none(uid=source_uid)
if p is None:
abort(404, description="Source not found")
all_members = p.members.all()
results = paginate_results(all_members, q_page, q_per_page)
return ordered_jsonify(results), 200
""" This class currently doesn't work with the `source_member_to_orm`
class AddMemberSchema(BaseModel):
user_email: str
role: Optional[MemberRole] = SourceMember.get_default_role()
is_active: Optional[bool] = True
class Config:
extra = "forbid"
json_schema_extra = {
"example": {
"user_email": "member@source.org",
"role": "ADMIN",
}
} """
# inviting anyone to NPDC
@bp.route("/invite", methods=["POST"])
@jwt_required()
@min_role_required(MemberRole.ADMIN)
# @validate(auth=True, json=InviteUserDTO)
def add_member_to_source():
body: InviteUserDTO = request.context.json
logger = logging.getLogger("add_member_to_source")
jwt_decoded = get_jwt()
current_user = User.get(jwt_decoded["sub"])
membership = current_user.sources.search(
uid=body.source_uid).first()
if (
membership is None
or not membership.is_administrator()
):
abort(403)
mail = current_app.extensions.get('mail')
invited_user = User.get_by_email(email=body.email)
source = Source.nodes.get_or_none(uid=body.source_uid)
if source is None:
return {
"status": "error",
"message": "Source not found!"
}, 404
if invited_user is not None:
invitation_exists = source.invitations.is_connected(
invited_user)
if invitation_exists:
return {
"status": "error",
"message": "Invitation already sent to this user!"
}, 409
else:
try:
new_invitation = Invitation(
role=body.role
).save()
source.invitations.connect(new_invitation).save()
invited_user.received_invitations.connect(new_invitation).save()
current_user.extended_invitations.connect(new_invitation).save()
msg = Message("Invitation to join an NPDC source organization!",
sender=TestingConfig.MAIL_USERNAME,
recipients=[body.email])
msg.body = "You have been invited to a join a source" + \
" organization. Please log on to accept or decline" + \
" the invitation at https://dev.nationalpolicedata.org/."
mail.send(msg)
return {
"status": "ok",
"message": "User notified of their invitation!"
}, 200
except Exception as e:
logger.exception(f"Failed to send invitation: {e}")
return {
"status": "error",
"message": "Something went wrong! Please try again!"
}, 500
else:
try:
existing_invitation = source.staged_invitations.search(
email=body.email
).first()
if existing_invitation is not None:
return {
"status": "error",
"message": "Invitation already sent to this user!"
}, 409
else:
new_staged_invite = StagedInvitation(
email=body.email, role=body.role).save()
source.staged_invitations.connect(new_staged_invite).save()
current_user.extended_staged_invitations.connect(
new_staged_invite).save()
msg = Message(
"Invitation to join NPDC index!",
sender=TestingConfig.MAIL_USERNAME,
recipients=[body.email])
msg.body = """You have been
invited to a source organization. Please register
with NPDC index at
https://dev.nationalpolicedata.org/."""
mail.send(msg)
return {
"status": "ok",
"message": """User is not registered with the NPDC index.
Email sent to user notifying them to register."""
}, 200
except Exception as e:
logger.exception(f"Failed to send invitation: {e}")
return {
"status": "error",
"message": "Something went wrong! Please try again!"
}, 500
# user can join org they were invited to
@bp.route("/join", methods=["POST"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate_request(CreateSource)
def join_organization():
logger = logging.getLogger("join_organization")
body: CreateSource = request.validated_body
jwt_decoded = get_jwt()
current_user = User.get(jwt_decoded["sub"])
source = Source.nodes.get_or_none(uid=body["source_uid"])
if source is None:
return {
"status": "error",
"message": "Source not found!"
}, 404
# invitations = current_user.invitations.all()
# TODO: Confirm that the user has a valid invitation to this organization.
# If not, return a 403 error.
# Note: currently inivtations are implemented as a Node... Perhaps a
# relationship would be more appropriate.
try:
body = request.get_json()
membership = current_user.sources.search(
uid=body["source_uid"]
).first()
if membership is not None:
return {
"status" : "Conflict",
"message": "User already in the organization"
}, 409
else:
current_user.sources.connect(
source,
{
"role": body["role"]
}
).save()
# TODO: Remove the invitation from the user's list of invitations
logger.info(f"User {current_user.uid} joined {source.name}")
return {
"status": "ok",
"message": "Successfully joined source organization"
} , 200
except Exception as e:
logger.exception(f"Failed to join organization: {e}")
return {
"status": "Error",
"message": "Something went wrong!"
}, 500
# user can leave org they already joined
@bp.route("/leave", methods=["DELETE"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
def leave_organization():
"""
Disconnect the user from the source organization.
"""
logger = logging.getLogger("leave_organization")
try:
body = request.get_json()
jwt_decoded = get_jwt()
current_user = User.get(jwt_decoded["sub"])
source = current_user.sources.search(
uid=body["source_uid"]
).first()
if source is not None:
current_user.sources.disconnect(
source
).save()
logger.info(f"User {current_user.uid} left {source.name}")
return {
"status": "ok",
"message": "Succesfully left organization"
}, 200
else:
return {
"status": "Error",
"message": "Not a member of this organization"
}, 400
except Exception as e:
logger.exception(
f"User {current_user.uid} failed to leave organization: {e}")
return {
"status": "Error",
"message": "Something went wrong!"
}
# admin can remove any member from a source organization
@bp.route("/remove_member", methods=['DELETE'])
@jwt_required()
@min_role_required(MemberRole.ADMIN)
def remove_member():
body = request.get_json()
logger = logging.getLogger("remove_member")
source = Source.nodes.get_or_none(uid=body["source_uid"])
current_user = User.get(get_jwt()["sub"])
user_to_remove = User.get(body["user_id"])
if source is None:
return {
"status": "error",
"message": "Source not found!"
}, 404
if user_to_remove is None:
return {
"status": "error",
"message": "User not found!"
}, 404
c_user_membership = current_user.sources.relationship(
source
).first()
if c_user_membership is None or not c_user_membership.is_administrator():
return {
"status": "Unauthorized",
"message": "Not authorized to remove members!"
}, 403
user_membership = user_to_remove.sources.relationship(
source
).first()
if user_membership is None:
return {
"status": "error",
"message": "User not a member of this organization!"
}, 404
try:
source.members.disconnect(user_to_remove).save()
user_to_remove.sources.disconnect(source).save()
return {
"status" : "ok",
"message" : "Member successfully deleted from Organization"
} , 200
except Exception as e:
logger.exception(
"Failed to remove user {} from {}: {}".format(
user_to_remove.uid,
source.name,
e
))
return {
"status" : "Error",
"message" : "Something went wrong!"
}, 500
# # admin can withdraw invitations that have been sent out
# @bp.route("/withdraw_invitation", methods=['DELETE'])
# @jwt_required()
# @min_role_required(MemberRole.ADMIN)
# def withdraw_invitation():
# body = request.get_json()
# try:
# user_found = Invitation.query.filter_by(
# user_id=body["user_id"],
# source_uid=body["source_uid"]
# ).first()
# if user_found:
# Invitation.query.filter_by(
# user_id=body["user_id"],
# source_uid=body["source_uid"]
# ).delete()
# db.session.commit()
# return {
# "status" : "ok",
# "message" : "Member's invitation withdrawn from Organization"
# } , 200
# else:
# return {
# "status" : "Error",
# "message" : "Member is not invited to the Organization"
# } , 400
# except Exception as e:
# db.session.rollback()
# return str(e)
# finally:
# db.session.close()
# # admin can change roles of any user
# @bp.route("/role_change", methods=["PATCH"])
# @jwt_required()
# @min_role_required(MemberRole.ADMIN)
# def role_change():
# body = request.get_json()
# try:
# user_found = SourceMember.query.filter_by(
# user_id=body["user_id"],
# source_uid=body["source_uid"]
# ).first()
# if user_found and user_found.role != "Administrator":
# user_found.role = body["role"]
# db.session.commit()
# return {
# "status" : "ok",
# "message" : "Role has been updated!"
# }, 200
# else:
# return {
# "status" : "Error",
# "message" : "User not found in this organization"
# }, 400
# except Exception as e:
# db.session.rollback
# return str(e)
# finally:
# db.session.close()
# # view invitations table
# @bp.route("/invitations", methods=["GET"])
# @jwt_required()
# @validate()
# # only defined for testing environment
# def get_invitations():
# if current_app.env == "production":
# abort(418)
# try:
# all_records = Invitation.query.all()
# records_list = [record.serialize() for record in all_records]
# return jsonify(records_list)
# except Exception as e:
# return str(e)
# # view staged invitations table
# @bp.route("/stagedinvitations", methods=["GET"])
# @jwt_required()
# @validate()
# # only defined for testing environment
# def stagedinvitations():
# if current_app.env == "production":
# abort(418)
# staged_invitations = StagedInvitation.query.all()
# invitations_data = [
# {
# 'id': staged_invitation.id,
# 'email': staged_invitation.email,
# 'role': staged_invitation.role,
# 'source_uid': staged_invitation.source_uid,
# }
# for staged_invitation in staged_invitations
# ]
# return jsonify({'staged_invitations': invitations_data})