-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
partners.py
555 lines (489 loc) · 16.5 KB
/
partners.py
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
from datetime import datetime
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 flask import Blueprint, abort, current_app, request, jsonify
from flask_jwt_extended import get_jwt
from flask_jwt_extended.view_decorators import jwt_required
from flask_sqlalchemy import Pagination
from sqlalchemy.orm import joinedload
from ..database import (
Partner,
PartnerMember,
MemberRole,
db,
Invitation,
StagedInvitation,
)
from ..dto import InviteUserDTO
from flask_mail import Message
from ..config import TestingConfig
from ..schemas import (
CreatePartnerSchema,
partner_orm_to_json,
partner_member_orm_to_json,
partner_to_orm,
validate,
AddMemberSchema,
partner_member_to_orm
)
bp = Blueprint("partner_routes", __name__, url_prefix="/api/v1/partners")
@bp.route("/<int:partner_id>", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate()
def get_partners(partner_id: int):
"""Get a single partner by ID."""
return partner_orm_to_json(Partner.get(partner_id))
@bp.route("/create", methods=["POST"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate(json=CreatePartnerSchema)
def create_partner():
"""Create a contributing partner."""
body = request.context.json
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 != ""
):
try:
partner = partner_to_orm(body)
except Exception:
abort(400)
partner_query_email = Partner.query.filter_by(
contact_email=body.contact_email).first()
partner_query_url = Partner.query.filter_by(url=body.url).first()
if partner_query_email:
return {
"status": "error",
"message": "Error. Entered email or url details "
+ "matches existing record.",
}, 400
if partner_query_url:
return {
"status": "error",
"message": "Error. Entered email or url details "
+ "matches existing record.",
}, 400
"""
add to database if all fields are present
and instance not already in db.
"""
created = partner.create()
resp = partner_orm_to_json(created)
make_admin = PartnerMember(
partner_id=created.id,
user_id=get_jwt()["sub"],
role=MemberRole.ADMIN,
)
make_admin.create()
# update to UserRole contributor status
user_id = get_jwt()["sub"]
user = User.query.filter_by(
id=user_id
).first()
user.role = UserRole.CONTRIBUTOR
track_to_mp(request, "create_partner", {
"partner_name": partner.name,
"partner_contact": partner.contact_email
})
return resp
else:
return {
"status": "error",
"message": "Failed to create partner. " +
"Please include all of the following"
}, 400
@bp.route("/", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate()
def get_all_partners():
"""Get all partners.
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_partners = db.session.query(Partner)
results = all_partners.paginate(
page=q_page, per_page=q_per_page, max_per_page=100
)
return {
"results": [partner_orm_to_json(partner) for partner in results.items],
"page": results.page,
"totalPages": results.pages,
"totalResults": results.total,
}
@bp.route("/<int:partner_id>/members/", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate() # type: ignore
def get_partner_members(partner_id: int):
"""Get all members of a partner.
Accepts Query ParaFmeters 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)
# partner = Partner.get(partner_id)
members: Pagination = (
PartnerMember.query.options(
joinedload(PartnerMember.user) # type: ignore
)
.filter_by(partner_id=partner_id)
.paginate(page=q_page, per_page=q_per_page, max_per_page=100)
)
return {
"results": [
partner_member_orm_to_json(member) for member in members.items
],
"page": members.page,
"totalPages": members.pages,
"totalResults": members.total,
}
""" This class currently doesn't work with the `partner_member_to_orm`
class AddMemberSchema(BaseModel):
user_email: str
role: Optional[MemberRole] = PartnerMember.get_default_role()
is_active: Optional[bool] = True
class Config:
extra = "forbid"
schema_extra = {
"example": {
"user_email": "[email protected]",
"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_partner():
body: InviteUserDTO = request.context.json
jwt_decoded = get_jwt()
current_user = User.get(jwt_decoded["sub"])
association = db.session.query(PartnerMember).filter(
PartnerMember.user_id == current_user.id,
PartnerMember.partner_id == body.partner_id,
).first()
if (
association is None
or not association.is_administrator()
or not association.partner_id == body.partner_id
):
abort(403)
mail = current_app.extensions.get('mail')
user = User.query.filter_by(email=body.email).first()
if user is not None:
invitation_exists = Invitation.query.filter_by(
partner_id=body.partner_id, user_id=user.id).first()
if invitation_exists:
return {
"status": "error",
"message": "Invitation already sent to this user!"
}, 500
else:
try:
new_invitation = Invitation(
partner_id=body.partner_id, user_id=user.id, role=body.role)
db.session.add(new_invitation)
db.session.commit()
msg = Message("Invitation to join NPDC partner organization!",
sender=TestingConfig.MAIL_USERNAME,
recipients=[body.email])
msg.body = """You are a registered user of NPDC and were invited
to a partner 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:
return {
"status": "error",
"message": "Something went wrong! Please try again!"
}, 500
else:
try:
new_staged_invite = StagedInvitation(
partner_id=body.partner_id, email=body.email, role=body.role)
db.session.add(new_staged_invite)
db.session.commit()
msg = Message("Invitation to join NPDC index!",
sender=TestingConfig.MAIL_USERNAME,
recipients=[body.email])
msg.body = """You are not a registered user of NPDC and were
invited to a partner 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:
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)
def join_organization():
try:
body = request.get_json()
user_exists = PartnerMember.query.filter_by(
user_id=body["user_id"],
partner_id=body["partner_id"]).first()
if user_exists:
return {
"status" : "Error",
"message": "User already in the organization"
}, 400
else:
new_member = PartnerMember(
user_id=body["user_id"],
partner_id=body["partner_id"],
role=body["role"],
date_joined=datetime.now(),
is_active=True
)
db.session.add(new_member)
db.session.commit()
Invitation.query.filter_by(
user_id=body["user_id"],
partner_id=body["partner_id"]).delete()
db.session.commit()
return {
"status": "ok",
"message": "Successfully joined partner organization"
} , 200
except Exception:
db.session.rollback()
return {
"status": "Error",
"message": "Something went wrong!"
}, 500
finally:
db.session.close()
# user can leave org they already joined
@bp.route("/leave", methods=["DELETE"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
def leave_organization():
"""
remove from PartnerMember table
"""
try:
body = request.get_json()
result = PartnerMember.query.filter_by(
user_id=body["user_id"], partner_id=body["partner_id"]).delete()
db.session.commit()
if result > 0:
return {
"status": "ok",
"message": "Succesfully left organization"
}, 200
else:
return {
"status": "Error",
"message": "Not a member of this organization"
}, 400
except Exception:
db.session.rollback()
return {
"status": "Error",
"message": "Something went wrong!"
}
finally:
db.session.close()
# admin can remove any member from a partner organization
@bp.route("/remove_member", methods=['DELETE'])
@jwt_required()
@min_role_required(MemberRole.ADMIN)
def remove_member():
body = request.get_json()
try:
user_found = PartnerMember.query.filter_by(
user_id=body["user_id"],
partner_id=body["partner_id"]
).first()
if user_found and user_found.role != MemberRole.ADMIN:
PartnerMember.query.filter_by(
user_id=body["user_id"],
partner_id=body["partner_id"]).delete()
db.session.commit()
return {
"status" : "ok",
"message" : "Member successfully deleted from Organization"
} , 200
else:
return {
"status" : "Error",
"message" : "Member is not part of the Organization"
} , 400
except Exception as e:
db.session.rollback()
return str(e)
finally:
db.session.close()
# 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"],
partner_id=body["partner_id"]
).first()
if user_found:
Invitation.query.filter_by(
user_id=body["user_id"],
partner_id=body["partner_id"]
).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 = PartnerMember.query.filter_by(
user_id=body["user_id"],
partner_id=body["partner_id"]
).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,
'partner_id': staged_invitation.partner_id,
}
for staged_invitation in staged_invitations
]
return jsonify({'staged_invitations': invitations_data})
@bp.route("/<int:partner_id>/members/add", methods=["POST"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate(json=AddMemberSchema)
def add_member_to_partner_testing(partner_id: int):
"""Add a member to a partner.
TODO: Allow the API to accept a user email instad of a user id
TODO: Use the partner ID from the API path instead of the request body
The `partner_member_to_orm` function seems very picky about the input.
I wasn't able to get it to accept a dict or a PartnerMember object.
Cannot be called in production environments
"""
if current_app.env == "production":
abort(418)
# Ensure that the user has premission to add a member to this partner.
jwt_decoded = get_jwt()
current_user = User.get(jwt_decoded["sub"])
association = (
db.session.query(PartnerMember)
.filter(
PartnerMember.user_id == current_user.id,
PartnerMember.partner_id == partner_id,
)
.first()
)
if (
association is None
or not association.is_administrator()
or not association.partner_id == partner_id
):
abort(403)
# TODO: Allow the API to accept a user email instad of a user id
# user_obj = User.get_by_email(request.context.json.user_email)
# if user_obj is None:
# abort(400)
# new_member = PartnerMember(
# partner_id=partner_id,
# user_id=user_obj.id,
# role=request.context.json.role,
# )
try:
partner_member = partner_member_to_orm(request.context.json)
except Exception:
abort(400)
created = partner_member.create()
track_to_mp(
request,
"add_partner_member",
{
"partner_id": partner_id,
"user_id": partner_member.user_id,
"role": partner_member.role,
},
)
return partner_member_orm_to_json(created)