-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
540 lines (495 loc) · 19.4 KB
/
app.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
from flask import Flask, request, url_for, abort, jsonify
from datetime import timedelta
from flask import render_template, redirect
from ldap_api import LdapApi, LdapApiException
from ldap3.utils import conv
from middleware import middleware
import token_handler
from os.path import join
from urllib.parse import unquote
import jwt
import json
import config
import mail
api = LdapApi(config)
app = Flask(__name__)
app.wsgi_app = middleware(app.wsgi_app)
def dn_to_uid(dn):
return dn.split(',')[0][4:]
def sanitize(x):
return conv.escape_filter_chars(x, encoding="utf-8")
# converts ldap-style objects to python dicts (yes, there is no better way)
def object_to_dict(obj):
dictionary = json.loads(obj.entry_to_json())["attributes"]
keys = dictionary.keys()
new_dictionary = {}
for key in list(keys):
if len(dictionary[key]) >= 1:
new_dictionary[key.replace("-", "_")] = dictionary[key][0]
else:
new_dictionary[key] = None
return new_dictionary
@app.route('/')
def homepage():
return abort(401) # Security by obscurity
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username')
password = request.json.get('password')
try:
successful, _ = api.check_user_password(username, password)
if successful:
token = token_handler.create_session_jwt_token(username)
return token
else:
abort(401), "Invalid credentials"
except Exception as e:
abort(403)
@app.route('/inactive_info', methods=['GET'])
def inactive_info():
uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if uid == None:
return abort(401)
inactive_user = None
try:
inactive_info = api.get_inactive_user(uid)
except LdapApiException as e:
return jsonify({
"inactive": False
})
# Get the owners of the group you are pending in
groups = api.get_groups_as_inactive_pending_member(uid)
if len(groups) != 1:
return jsonify({
"inactive": True
})
group = groups[0]
group_name = str(group.cn)
pending_group_owners = [object_to_dict(api.get_user(dn_to_uid(str(x)))) for x in group.owner]
return jsonify({
"inactive": True,
"pending_group_name": group_name,
"pending_group_owners": pending_group_owners,
})
@app.route('/whoami', methods=['GET'])
def whoami():
uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if uid == None:
return abort(401)
info = api.get_user_info(uid)
return object_to_dict(info)
@app.route('/users', methods=['GET'])
def users():
""" Lists all users. Returns their uids in a json array.
To access this, one must be owner in some group.
"""
# Check if user is admin in some group
uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if uid == None:
return abort(401)
if not api.is_active(uid):
return abort(401)
if not api.is_group_owner_anywhere(uid):
return abort(403), "To access this endpoint, you have to be owner of a group"
# Ok, they are. List all users and return them!
all_users = [object_to_dict(x) for x in api.get_users()]
return jsonify(all_users)
@app.route('/users/set_new_password_with_old_password', methods=['POST'])
def user_set_password_with_old():
""" Sets a new password using the old one. Takes a json body containing
the keys old_password and new_password. Says ok when done, 401 when not ok.
You need to be logged in to do this.
"""
uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if uid == None:
return abort(401)
old_password = request.json.get('old_password')
new_password = request.json.get('new_password')
successful, _ = api.check_user_password(uid, old_password)
if successful:
api.set_user_password(uid, new_password)
return "ok", 200
else:
return "invalid old password", 401
@app.route('/users/set_password_with_key', methods=['POST'])
def user_set_password_with_key():
""" Sets a new password using a password key that is sent via email.
Takes a json body containing the keys "key" and "new_password".
Says ok when done, 401 when not ok. You don't need to be logged in to do this.
"""
token_str = request.json.get('key')
uid = token_handler.get_token_user_with_string(token_str)
if uid == None:
return abort(401)
new_password = request.json.get('new_password')
api.set_user_password(uid, new_password)
return "ok", 200
@app.route('/users/reset_password', methods=['POST'])
def user_reset_password():
""" Starts the reset password process by sending a reset mail to the alternative_mail.
You don't need to be logged in to do this.
"""
alternative_mail = request.json.get('alternative_mail')
try:
user = api.get_user_by_alternative_mail(alternative_mail)
if user == None:
# You can't let people guess mails!
return "ok"
password_reset_token = token_handler.create_password_reset_jwt_token(user.uid[0]).decode("utf-8")
mail.send_email(alternative_mail, "Passwort-Reset", "emails/password_reset_email", {
"name": user.uid[0],
"link": join(config.FRONTEND_URL, "confirm/password?key=" + password_reset_token),
})
return "ok"
except LdapApiException as e:
# You can't let people guess mails!
return "ok"
@app.route('/users/set_alternative_mail', methods=['POST'])
def set_alternative_mail():
""" Starts the email confirmation process by sending an email.
Takes a json body with the key "alternative_mail".
"""
alternative_mail = request.json.get('alternative_mail')
uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if uid == None:
return abort(401)
try:
email_reset_token = token_handler.create_email_confirmation_jwt_token(uid, alternative_mail).decode("utf-8")
mail.send_email(alternative_mail, "Email-Confirmation", "emails/email_confirmation", {
"name": uid,
"link": join(config.DASHBOARD_URL, "confirm?key=" + email_reset_token),
})
return "ok"
except LdapApiException as e:
print(e)
return abort(401)
@app.route('/groups', methods=['GET'])
def groups():
""" Gets all groups. Returns them as json:
[
{
"businessCategory": "...",
"cn": "...",
"ou": "...",
},
...
]
"""
username = token_handler.get_jwt_user(request.headers.get('Authorization'))
if username == None:
return abort(401)
if not api.is_active(username):
return abort(401)
groups = [object_to_dict(x) for x in api.get_groups()]
return jsonify(groups)
@app.route('/my_groups', methods=['GET'])
def mygroups():
""" Gets all of the groups you are a member of. Returns them as json:
[
{
"businessCategory": "...",
"cn": "...",
"ou": "...",
"membership": "...", // Either "pending", "member", or "admin"
},
...
]
"""
username = token_handler.get_jwt_user(request.headers.get('Authorization'))
if username == None:
return abort(401)
if not api.is_active(username):
return abort(401)
pending_groups = [object_to_dict(x) for x in api.get_groups_as_active_pending_member(username)]
member_groups = [object_to_dict(x) for x in api.get_groups_as_member(username)]
owned_groups = [object_to_dict(x) for x in api.get_groups_as_owner(username)]
# Groups can overlap. If you're owner you're always also member.
# But the interesting information is that you're owner.
member_groups = list(filter(lambda x: x not in owned_groups, member_groups))
# Add information about membership
for group in pending_groups:
group['membership'] = 'pending'
for group in member_groups:
group['membership'] = 'member'
for group in owned_groups:
group['membership'] = 'admin'
all_groups = []
all_groups.extend(pending_groups)
all_groups.extend(member_groups)
all_groups.extend(owned_groups)
return jsonify(all_groups)
@app.route('/groups/<group_id>/members', methods=['GET'])
def group_members(group_id):
group_id = sanitize(group_id)
uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if uid == None:
return abort(401)
if not api.is_active(uid):
return abort(401)
if not any(x.uid == uid for x in api.get_group_owners(group_id)):
return abort(401)
ldap_members = api.get_group_members(group_id)
members = []
for x in ldap_members:
try:
members.append(object_to_dict(x))
except Exception as e:
print(e)
return jsonify(members)
@app.route('/groups/<group_id>/guests', methods=['GET'])
def group_guests(group_id):
group_id = sanitize(group_id)
uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if uid == None:
return abort(401)
if not api.is_active(uid):
return abort(401)
if not any(x.uid == uid for x in api.get_group_owners(group_id)):
return abort(401)
ldap_members = api.get_group_guests(group_id)
members = []
for x in ldap_members:
try:
members.append(object_to_dict(x))
except Exception as e:
print(e)
return jsonify(members)
@app.route('/groups/<group_id>/active_pending_members', methods=['GET'])
def group_active_pending_members(group_id):
group_id = sanitize(group_id)
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
if not any(x.uid == my_uid for x in api.get_group_owners(group_id)):
return abort(401)
ldap_members = api.get_group_active_pending_members(group_id)
members = []
for x in ldap_members:
try:
members.append(object_to_dict(x))
except Exception as e:
print(e)
return jsonify(members)
@app.route('/groups/<group_id>/inactive_pending_members', methods=['GET'])
def group_inactive_pending_members(group_id):
group_id = sanitize(group_id)
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
if not any(x.uid == my_uid for x in api.get_group_owners(group_id)):
return abort(401)
ldap_members = api.get_group_inactive_pending_members(group_id)
members = []
for x in ldap_members:
try:
members.append(object_to_dict(x))
except Exception as e:
print(e)
return jsonify(members)
@app.route('/groups/<group_id>/owners', methods=['GET'])
def group_owners(group_id):
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
group_id = sanitize(group_id)
ldap_owners = api.get_group_owners(group_id)
owners = []
for x in ldap_owners:
try:
owners.append(object_to_dict(x))
except Exception as e:
print(e)
return jsonify(owners)
@app.route('/groups/<group_id>/add_member', methods=['POST'])
def add_user_to_group(group_id):
group_id = sanitize(group_id)
uid = sanitize(request.json.get('uid'))
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
if not any(x.uid == my_uid for x in api.get_group_owners(group_id)):
return abort(401)
api.add_group_member(group_id, uid)
return "ok"
@app.route('/groups/<group_id>/remove_member', methods=['POST'])
def remove_user_from_group(group_id):
""" Removes a user from a group. Call this function if you want to either remove
yourself from a group or you want to remove another user from a group as an owner.
If an owner removes a user from allgemein, their entire account is deleted.
If a user is not part of any group after removal, their entire account is deleted.
"""
group_id = sanitize(group_id)
uid = sanitize(request.json.get('uid'))
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
# 1st: Is the uid the group?
if not (any(x.uid == uid for x in api.get_group_guests(group_id)) or any(x.uid == uid for x in api.get_group_members(group_id))):
return abort(400)
# User is not Dashboardadmin, cause dashboardadmin is holy
if (uid == "dashboardadmin"):
return abort(400)
# 2nd: Is the user an admin or just a user
if any(x.uid == my_uid for x in api.get_group_owners(group_id)):
# Group owners can remove anyone from a group but themself
if uid == my_uid:
return abort(400) # admin tried to remove oneself
api.remove_group_member(group_id, uid) # remove
# If user removed from allgemein or from their last group, remove the user
if group_id == "allgemein" or \
(api.get_groups_as_member(uid) == [] and api.get_groups_as_owner(uid) == [] and api.get_groups_as_active_pending_member(uid) == []):
api.delete_user(uid)
return "ok"
else:
# Users can remove themselves from any group but allgemein
if uid == my_uid and any(x.uid == uid for x in api.get_group_members(group_id)) and not group_id == "allgemein":
api.remove_group_member(group_id, uid)
return "ok"
return abort(500)
@app.route('/groups/<group_id>/add_owner', methods=['POST'])
def add_owner_to_group(group_id):
group_id = sanitize(group_id)
uid = sanitize(request.json.get('uid'))
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
if not any(x.uid == my_uid for x in api.get_group_owners(group_id)):
return abort(401)
api.add_group_owner(group_id, uid)
return "ok"
@app.route('/groups/<group_id>/remove_owner', methods=['POST'])
def remove_owner_from_group(group_id):
group_id = sanitize(group_id)
uid = sanitize(request.json.get('uid'))
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
# Auth is missing
if my_uid == None:
return abort(401)
# User is inactive
if not api.is_active(my_uid):
return abort(401)
# User is not an owner
if not any(x.uid == my_uid for x in api.get_group_owners(group_id)):
return abort(401)
# User is not Dashboardadmin, cause dashboardadmin is holy
if (uid == "dashboardadmin"):
return abort(401)
# User is the ownly owner despite dashboardadmin
if not any((x.uid != "dashboardadmin" and x.uid != my_uid) for x in api.get_group_owners(group_id)):
return abort(401)
api.remove_group_owner(group_id, uid)
return "ok"
@app.route('/groups/<group_id>/add_guest', methods=['POST'])
def add_guest_to_group(group_id):
group_id = sanitize(group_id)
guest_name = sanitize(request.json.get('name'))
guest_mail = sanitize(request.json.get('mail'))
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
if not any(x.uid == my_uid for x in api.get_group_owners(group_id)):
return abort(401)
uid = api.create_guest(guest_name, guest_mail)
api.add_group_member(group_id, uid)
group = api.get_group(group_id)
mail.send_email(str(guest_mail), "Du bist jetzt im Verteiler " + str(group.cn), \
"emails/guest_invite_email", {
"name": str(guest_name),
"group_name": str(group.cn),
})
return uid
@app.route('/groups/<group_id>/request_access', methods=['POST'])
def request_access_to_group(group_id):
group_id = sanitize(group_id)
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
api.add_group_active_pending_member(group_id, my_uid)
group = api.get_group(group_id)
user = api.get_user(my_uid)
for owner in api.get_group_owners(group_id):
mail.send_email(str(owner.mail), "Neue Anfrage in " + str(group.cn), \
"emails/new_pending_member_mail", {
"name": str(owner.cn),
"group_name": str(group.cn),
"dashboard_url": config.FRONTEND_URL,
"new_member_name": str(user.cn)
})
return "ok"
@app.route('/groups/<group_id>/accept_pending_member', methods=['POST'])
def accept_pending_member(group_id):
group_id = sanitize(group_id)
uid = sanitize(request.json.get('uid'))
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
if not any(x.uid == my_uid for x in api.get_group_owners(group_id)):
return abort(401)
if any(x.uid == uid for x in api.get_group_inactive_pending_members(group_id)):
api.activate_user(uid)
api.remove_group_active_pending_member(group_id, uid)
api.add_group_member(group_id, uid)
return "ok"
@app.route('/groups/<group_id>/remove_pending_member', methods=['POST'])
def remove_pending_member_from_group(group_id):
""" Cancels a membership request. Call this function if you want to either remove
your own membership request from a group or you want to remove another user's request
from a group as an owner.
"""
group_id = sanitize(group_id)
uid = sanitize(request.json.get('uid'))
my_uid = token_handler.get_jwt_user(request.headers.get('Authorization'))
if my_uid == None:
return abort(401)
if not api.is_active(my_uid):
return abort(401)
# Users can remove their own requests from a group
if uid == my_uid and any(x.uid == uid for x in api.get_group_active_pending_members(group_id)):
api.remove_group_active_pending_member(group_id, uid)
return "ok"
# Group owners can remove any pending member
if any(x.uid == my_uid for x in api.get_group_owners(group_id)):
api.remove_group_active_pending_member(group_id, uid)
return "ok"
return abort(401)
@app.route('/confirm', methods=['GET'])
def confirm_mail():
token_str = request.args.get('key')
token_type = None
try:
token = jwt.decode(token_str, config.JWT_SECRET, algorithms=['HS256'])
if token["type"] == "password_reset":
pass
elif token["type"] == "email_confirmation":
api.set_user_mail(sanitize(token["username"]), sanitize(token["email"]))
else:
return abort(400)
token_type = token["type"]
except jwt.InvalidTokenError:
return abort(401)
redirect_url = None
if token_type == None:
return abort(401)
elif token_type == "password_reset":
redirect_url = config.FRONTEND_URL + "/confirm/password?key=" + token_str
elif token_type == "email_confirmation":
redirect_url = config.FRONTEND_URL + "/confirm/email"
return redirect(unquote(redirect_url), code=302)