This repository has been archived by the owner on Jan 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
views.py
695 lines (580 loc) · 22.2 KB
/
views.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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
from .authentication import ExpiringTokenAuthentication, \
ValidatingTokenAuthentication
from .models import Booking, BookingSociety, UserProfile, Room, Verifier, \
ShibLoginToken, WhiteList
import datetime
import pytz
import json
import base64
import requests
import urllib.parse
import urllib.request
from django.contrib.auth import authenticate, logout
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import Group, User
from django.shortcuts import render
from django.template.context_processors import csrf
from django.http import HttpResponse
from rest_framework import permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes, \
authentication_classes
from rest_framework.response import Response
from constants import *
from . import utils
@api_view(['GET', 'POST'])
def no_access(request):
return Response({"error": "You do not have appropiate permissions."})
@api_view(['GET'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
def get_rooms_list(request):
rooms = Room.objects.all()
room_dict = []
for room in rooms:
room_dict.append({
"capacity": room.capacity,
"coffee": room.coffee,
"water_fountain": room.water_fountain,
"room_name": room.name,
"individual_access": room.indiv_bookable,
"printers": room.printers,
"room_id": room.room_id
})
return Response(room_dict)
@api_view(['GET'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
@permission_required('rooms.can_generate_tokens', raise_exception=True)
def obtain_expiring_auth_token(request):
local_tz = pytz.timezone('Europe/Moscow')
try:
soc_id = request.GET.get("society_id")
except:
return Response({"error": "Society ID could not be found."})
try:
society = User.objects.get(username=soc_id)
except:
return Response({"error": "Society ID does not exist."})
if (
society.user_profile not in
request.user.user_profile.associated_society.all()
):
return Response({"error": "User does not belong to the society."})
token, created = Token.objects.get_or_create(user=society)
utc_now = datetime.datetime.utcnow() - datetime.timedelta(days=100)
utc_now = pytz.utc.localize(utc_now, is_dst=None).astimezone(local_tz)
if not created and token.created < utc_now:
token.delete()
token = Token.objects.create(user=society)
token.created = datetime.datetime.utcnow()
token.save()
return Response({'token': token.key})
@api_view(['GET'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
def get_room_bookings(request):
try:
room_id = request.GET.get("room_id")
date = request.GET.get("date")
except:
return Response({"error": "Room ID or Date has not been found."})
try:
room = Room.objects.get(room_id=room_id)
except:
return Response({"error": "Room ID does not exist."})
finally:
pass
try:
dateString = date
dateOfSearch = datetime.datetime.strptime(dateString, "%Y%m%d").date()
except:
return Response({"error": "Invalid Date has been entered."})
bookings = list(Booking.objects.filter(date=dateOfSearch, room=room))
bookings.extend(
list(BookingSociety.objects.filter(date=dateOfSearch, room=room)))
booking_dict = []
for booking in (bookings):
booking_dict.append({
"username": (booking.user.user.username),
"start": booking.start,
"end": booking.end,
"notes": booking.remarks if isinstance(booking, Booking) else
booking.remarks + " -" + booking.society.user.first_name
})
return Response(booking_dict)
@api_view(['GET'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
def get_user_meta_data(request):
user = request.user
return Response({
"email": user.email,
"quota_left": user.user_profile.quota_left,
"societies": [
[k.user.first_name, k.user.username] for k in
user.user_profile.associated_society.all()
],
"groups": [k.name for k in user.groups.all()]
})
@api_view(['GET'])
def login_get_token(request):
sid = "shib" + utils.random_string(60)
login_token = ShibLoginToken(sid=sid)
login_token.save()
callback_url = ROOT_URL + 'user.login.callback?sid=' + sid
return Response({
"loginUrl": SHIB_URL + "Login?target=" +
urllib.parse.quote_plus(callback_url),
"callbackUrl": callback_url,
"sid": sid,
"stream_sub_url": STREAM_SUBSCRIBE_URL + sid,
"stream_sub_lp_url": STREAM_SUBSCRIBE_LP_URL + sid
})
@api_view(['POST'])
def login_status(request):
try:
data = json.loads(request.body.decode('utf-8'))
sid = data["sid"]
except:
return Response({"error": "No sid supplied"})
try:
sid_data = ShibLoginToken.objects.get(sid=sid)
except:
return Response({"error": "Invalid sid"})
if sid_data.status == 0:
return Response({"success": "OK", "status": "NOT_LOGGED_IN"})
elif sid_data.status == 1:
token, created = Token.objects.get_or_create(user=sid_data.user)
user_data = {
"email": sid_data.user.email,
"quota_left": sid_data.user.user_profile.quota_left,
'token': token.key,
"societies": [
[k.user.first_name, k.user.username] for k in
sid_data.user.user_profile.associated_society.all()
],
"groups": [k.name for k in sid_data.user.groups.all()]
}
return Response(
{
"success": "OK",
"status": "LOGGED_IN",
"user_data": user_data
})
else:
return Response({"success": "OK", "status": "LOGIN_ERROR"})
def is_summer_postgrad(groups):
return ("engscifac-pg" in groups
and datetime.datetime.today() < datetime.datetime(2017, 9, 30))
def login_callback(request):
try:
sid = request.GET['sid']
except:
return HttpResponse('No sid supplied, so login cannot continue.')
try:
sid_data = ShibLoginToken.objects.get(sid=sid)
except ShibLoginToken.DoesNotExist:
return HttpResponse('Invalid sid. Please try logging in again.')
try:
eppn = request.META['HTTP_EPPN']
groups = request.META['HTTP_UCLINTRANETGROUPS']
cn = request.META['HTTP_CN']
department = request.META['HTTP_DEPARTMENT']
given_name = request.META['HTTP_GIVENNAME']
surname = request.META['HTTP_SN']
except:
return HttpResponse(
'No Shibboleth data. This page should not be accessed directly!')
# check if the user is in the internal whitelist
white_listed = WhiteList.objects.filter(eppn=eppn).exists()
if ("engscifac-ug" not in groups.split(';') and not white_listed
and not is_summer_postgrad(groups.split(';'))):
login_response = {
"result": "failure",
"message": ("This system is available only"
" to members of the engineering faculty.")
}
else:
if User.objects.filter(email=eppn).exists():
user = User.objects.get(email=eppn)
else:
User.objects.create_user(
username=cn,
email=eppn,
password=utils.random_string(128),
first_name=given_name,
last_name=surname
)
user = User.objects.get(email=eppn)
group_2 = Group.objects.get(name="Group_2")
user.groups.add(group_2)
user.save()
up = UserProfile(user=user)
up.department = department
up.save()
token, created = Token.objects.get_or_create(user=user)
token.save()
login_response = {
"result": "success",
"message": "Login successful",
"email": user.email,
"quota_left": user.user_profile.quota_left,
'token': token.key,
"societies": [
[k.user.first_name, k.user.username] for k in
user.user_profile.associated_society.all()
],
"groups": [k.name for k in user.groups.all()]
}
try:
t = ShibLoginToken.objects.get(user=user)
if t.sid != sid:
t.delete()
except ShibLoginToken.DoesNotExist:
print(("User has never tried logging in before,"
" so there was nothing to delete. Continuing..."))
try:
token = ShibLoginToken.objects.get(sid=sid)
token.status = 1
token.user = user
token.save()
except Exception as e:
print("Error updating token in database")
print(e)
url = STREAM_PUBLISH_URL + "/?id=" + sid
try:
login_response_str = json.dumps(login_response)
b64 = base64.b64encode(login_response_str.encode('utf-8'))
r = requests.post(url, data=b64)
print(r.text)
except Exception as e:
print("Error sending the data to stream backend")
print(e)
response = HttpResponse(content_type="text/html")
response.write(login_response)
return response
# this method is called logout_view so that it does not clash with built-in's
# logout() method from django.contrib.auth
@api_view(['GET'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
def logout_view(request):
if request.method == 'GET':
token, created = Token.objects.get_or_create(user=request.user)
token.delete()
logout(request)
return Response({"success": "You have been logged out."})
return Response({"success": False})
@api_view(['POST'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication,
ExpiringTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
def book_room(request):
if (request.POST.get("society_booking") == "True" and
request.user.groups.filter(name='Group_3').exists()):
try:
room_id = request.POST["room_id"]
date = request.POST["date"]
start_time = request.POST["start_time"]
end_time = request.POST["end_time"]
# TODO: change to society ID
society = request.POST["society"]
event_name = request.POST["event_name"]
except:
return Response({
"error": "Could not parse the POST request data."})
try:
soc = User.objects.get(username=society)
except:
return Response({"error": "Bad society ID."})
if (
soc.user_profile not in
request.user.user_profile.associated_society.all()
):
return Response({
"error": "Permission denied with this society access."
})
try:
room = Room.objects.get(room_id=room_id)
except:
return Response({"error": "Room ID does not exist."})
return book_a_room(
request,
room,
date,
start_time,
end_time,
is_society_booking=True,
meta_data={
"event_name": event_name,
"society": soc.user_profile
})
elif request.POST.get("society_booking") == "False":
try:
room_id = request.POST["room_id"]
date = request.POST["date"]
start_time = request.POST["start_time"]
end_time = request.POST["end_time"]
notes = request.POST["notes"]
except:
return Response({
"error": "Could not parse the POST request data."})
try:
room = Room.objects.filter(room_id=room_id, indiv_bookable=True)[0]
except:
return Response({
"error": ("No permissions to access this room"
"or room does not exist.")
})
return book_a_room(request, room, date, start_time, end_time,
is_society_booking=False, meta_data={"notes": notes}
)
else:
return Response(
{"error": "You don't have permission to book this room"})
def book_a_room(request, room, date, start_time,
end_time, is_society_booking, meta_data):
# Only allow block bookings, start time should be HH:01 and end should be
# HH:00
if not (start_time[3:] == "01" and end_time[3:] == "00"):
return Response({
"error": "Time block should be in the format HH:01 and HH:00."
})
current_user = request.user.user_profile
try:
start_time = utils.convertTime(start_time)
end_time = utils.convertTime(end_time)
dateString = date
dateOfSearch = datetime.datetime.strptime(dateString, "%Y%m%d").date()
except:
return Response({"error": "Invalid date or time given."})
# date validitiy checking
days_ahead = (dateOfSearch - datetime.datetime.now().date()).days
if is_society_booking:
if days_ahead > 21:
return Response({
"error": ("Societies are not allowed to book rooms"
" more than 3 weeks in advance")
})
else:
if current_user.user.groups.filter(name="Group_1").exists():
if days_ahead > 90:
return Response(
{
"error": ("You are not allowed to book"
" more than 90 days in advance.")
})
else:
if days_ahead > 7:
return Response({
"error": ("You are not allowed to book"
" more than 7 days in advance.")
})
if is_time_valid(dateOfSearch, start_time, end_time)["success"]:
if checkAvailability(
room, dateOfSearch, start_time, end_time)["success"]:
return _book_room(current_user, room, dateOfSearch,
start_time, end_time, is_society_booking,
meta_data)
else:
return Response({"error": "This slot has already been booked."})
else:
return Response(is_time_valid(
dateOfSearch, start_time, end_time)["error"])
def _book_room(current_user, room, dateOfSearch, start_time,
end_time, is_society_booking, meta_data):
# quota checking and reductions
if not current_user.user.groups.filter(
name='Group_1').exists() and not is_society_booking:
minutes = (
datetime.datetime.combine(datetime.date.today(), end_time) -
datetime.datetime.combine(datetime.date.today(), start_time))
if (minutes.seconds // 60) > current_user.quota_left:
return Response({"error": "You do not have enough quota left."})
else:
current_user.quota_left -= (minutes.seconds // 60 + 1)
current_user.save()
if is_society_booking:
instance = BookingSociety(
user=current_user,
room=room,
date=dateOfSearch,
start=start_time,
end=end_time,
society=meta_data["society"],
remarks=meta_data["event_name"]
)
instance.save()
else:
instance = Booking(
user=current_user,
room=room,
date=dateOfSearch,
start=start_time,
end=end_time,
remarks=meta_data["notes"]
)
instance.save()
return Response({"success": True})
def is_time_valid(date, start_time, end_time):
if end_time <= start_time:
return {"success": False, "error": {"error": "Invalid times given."}}
dayMode = utils.weekOrWeekend(date)
if end_time > CLOSING_TIME[dayMode]:
return {"success": False, "error": {
"error": "Choose an end time before closing time."}}
if start_time < OPENING_TIME[dayMode]:
return {"success": False, "error": {
"error": "Choose a starting time after opening time."}}
return {"success": True}
def checkAvailability(room, date, start_time, end_time):
soc_bookings = BookingSociety.objects.filter(room=room, date=date)
normal_bookings = Booking.objects.filter(room=room, date=date)
booking_times = list(map(lambda k: (k.start, k.end),
(list(soc_bookings) + list(normal_bookings))))
for booking in booking_times:
if (start_time <= booking[1] and booking[0] <= end_time):
return {
"success": False,
"error": {"error": "This slot has already been booked."}
}
return {"success": True}
@api_view(['GET'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
def get_users_booking(request):
current_user = request.user.user_profile
bookings = list(Booking.objects.filter(
user=current_user, date__gte=datetime.date.today()))
if len(current_user.associated_society.all()):
bookings.extend(
list(BookingSociety.objects.filter(
user=current_user, date__gte=datetime.date.today())))
# serialize the data and send it back
retDict = []
for booking in bookings:
retDict.append({
"username": booking.user.user.username,
"start": booking.start,
"end": booking.end,
"booking_id": booking.booking_id,
"date": booking.date,
"room_name": booking.room.name,
"notes": booking.remarks if isinstance(booking, Booking) else
booking.remarks + " -" + booking.society.user.first_name
})
return Response(retDict)
@api_view(['GET'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
def delete_booking(request):
try:
id = request.GET.get("booking_id")
except:
return Response({"error": "No booking_id has been found."})
try:
booking = Booking.objects.get(booking_id=id)
except:
try:
booking = BookingSociety.objects.get(booking_id=id)
except:
return Response({"error": "No booking has been found"})
if request.user.user_profile != booking.user:
return Response(
{"error": "The booking does not belong to you."})
booking_time = datetime.datetime.combine(booking.date, booking.start)
if booking_time - datetime.datetime.now() > datetime.timedelta(hours=6):
minutes = (
datetime.datetime.combine(datetime.date.today(), booking.end) -
datetime.datetime.combine(datetime.date.today(), booking.start))
booking.user.quota_left += (minutes.seconds // 60 + 1)
booking.user.save()
booking.delete()
return Response({"success": True})
@api_view(['POST'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
@permission_required('rooms.can_add_and_remove_people_to_group_3')
def add_user_to_group3(request):
current_user = request.user
try:
username = request.POST.get("username")
soc_id = request.POST.get("society_id")
except:
return Response({"error": "Parsing has failed."})
try:
society = User.objects.get(username=soc_id)
except:
return Response({"error": "Society ID does not exist."})
try:
user = User.objects.get(username=username)
except:
return Response({"error": "Username does not exist."})
if (society.user_profile not in
current_user.user_profile.associated_society.all()):
return Response({"error": "You do not belong to this society."})
group_3 = Group.objects.get(name='Group_3')
user.groups.add(group_3)
user.user_profile.associated_society.add(society.user_profile)
user.user_profile.society_access = True
user.user_profile.save()
user.save()
return Response({"success": "Successfully added " +
username + " to society access groups!"})
@api_view(['POST'])
@authentication_classes(
(SessionAuthentication, ValidatingTokenAuthentication)
)
@permission_classes((permissions.IsAuthenticated,))
@permission_required('rooms.can_add_and_remove_people_to_group_3')
def remove_user_from_group3(request):
current_user = request.user
try:
username = request.POST.get("username")
soc_id = request.POST.get("society_id")
except:
return Response({"error": "Parsing has failed."})
try:
user = User.objects.get(username=username)
except:
return Response({"error": "Username does not exist."})
try:
society = User.objects.get(username=soc_id)
except:
return Response({"error": "Society ID does not exist."})
if (society.user_profile not in
current_user.user_profile.associated_society.all()):
return Response({"error": "You do not belong to this society."})
user.user_profile.associated_society.remove(society.user_profile)
user.user_profile.save()
user.save()
if len(user.user_profile.associated_society.all()) == 0:
group_3 = Group.objects.get(name='Group_3')
try:
group_3.user_set.remove(user)
except:
return Response({"error": "User was not in Group3."})
user.user_profile.society_access = False
user.user_profile.save()
user.save()
return Response({"success": True})