views.py 21.5 KB
Newer Older
1
2
# standard library imports
from __future__ import absolute_import, print_function
3
# core django imports
Daniel W Bond's avatar
Daniel W Bond committed
4
from django.shortcuts import get_object_or_404
5
from django.http import HttpResponseForbidden
6
7
from django.views.generic import (CreateView, ListView, DetailView, UpdateView,
                                  FormView, DeleteView)
8
from django.core.urlresolvers import reverse
9
10
from django.contrib import messages
from django.utils.safestring import mark_safe
11
from django.forms.widgets import HiddenInput
12
# third party imports
13
from braces.views import LoginRequiredMixin, FormValidMessageMixin
14
from cas.views import login as cas_login
15
from ratelimit.decorators import ratelimit
16
# imports from your apps
17
from .models import Student, Major, Room, Confirmation
18
from .forms import StudentUpdateForm, WelcomeNameForm, WelcomePrivacyForm
19

Daniel W Bond's avatar
Daniel W Bond committed
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
not_started = """Welcome to SRCT Roomlist! <a href="%s">Click here</a> to walk through
                 your profile setup."""

# 1 or 2
started = """Welcome back to SRCT Roomlist! It looks like you're not quite finished with
             setting up your profile. <a href="%s">Click here</a> to return to your
             welcome walkthrough."""

# 3
almost = """Welcome back to SRCT Roomlist! It looks like you're almost finished
            with setting up your profile. <a href="%s">Click here</a> to return
            to the last page of your welcome walkthrough."""

# walkthrough finished but Room is None
no_room = """It looks like you haven't set your room yet. Head to <a href="%s"> your
             settings page</a> to get that taken care of."""


def custom_cas_login(request, *args, **kwargs):
    response = cas_login(request, *args, **kwargs)
    # returns HttpResponseRedirect
    if request.user.is_authenticated():

        if request.user.student.completedName is False:
            rendered_url = reverse('welcomeName', args=[request.user.username])
            add_url = not_started % rendered_url
            messages.add_message(request, messages.INFO, mark_safe(add_url))

        elif request.user.student.completedPrivacy is False:
            rendered_url = reverse('welcomePrivacy', args=[request.user.username])
            add_url = started % rendered_url
            messages.add_message(request, messages.INFO, mark_safe(add_url))

        elif request.user.student.completedMajor is False:
            rendered_url = reverse('welcomeMajor', args=[request.user.username])
            add_url = started % rendered_url
            messages.add_message(request, messages.INFO, mark_safe(add_url))

        elif request.user.student.completedName is False:
            rendered_url = reverse('welcomeSocial', args=[request.user.username])
            add_url = started % rendered_url
            messages.add_message(request, messages.INFO, mark_safe(add_url))

        elif request.user.student.room is None:
            rendered_url = reverse('updateStudent', args=[request.user.username])
            add_url = started % rendered_url
            messages.add_message(request, messages.INFO, mark_safe(add_url))
        # eventually add a reminder if the privacy is set to students
        # one in ten change will display a reminder and link to change

    return response


74
75
def on_the_same_floor(student, confirmer):
    if student == confirmer:
76
        # Student is confirmer
77
78
79
80
81
        return False
    student_floor = student.get_floor()
    confirmer_floor = confirmer.get_floor()
    # room hasn't been set yet
    if (student_floor is None) or (confirmer_floor is None):
82
        # one Student is None
83
84
        return False
    elif not(student_floor == confirmer_floor):
85
        # not the same floor
86
87
88
89
90
        return False
    else:
        return True


91
92
93
# details about the student
class DetailStudent(LoginRequiredMixin, DetailView):
    model = Student
94
95
96
97
    context_object_name = 'student'
    template_name = 'detailStudent.html'

    login_url = 'login'
Daniel W Bond's avatar
Daniel W Bond committed
98
99
100
101
102
103
104
105

    def get_context_data(self, **kwargs):
        context = super(DetailStudent, self).get_context_data(**kwargs)

        # requesting_student = Student.objects.get(user=self.request.user)
        requesting_student_filter = Student.objects.filter(user=self.request.user)
        requesting_student = requesting_student_filter[0]

106
107
108
109
110
        same_floor = on_the_same_floor(self.get_object(), requesting_student)

        flags = Confirmation.objects.filter(confirmer=requesting_student,
                                            student=self.get_object()).count()

Daniel W Bond's avatar
Daniel W Bond committed
111
112
113
114
115
        if flags:
            try:
                my_flag = Confirmation.objects.get(confirmer=requesting_student,
                                                   student=self.get_object())
            except Exception as e:
116
117
                print("Students are not supposed to be able to make more than one flag per student.")
                print(e)
118

Daniel W Bond's avatar
Daniel W Bond committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        def onFloor():
            floor_status = False
            if requesting_student.get_floor() == self.get_object().get_floor():
                floor_status = True
            return floor_status

        def inBuilding():
            floor_status = False
            if requesting_student.get_building() == self.get_object().get_building():
                floor_status = True
            return floor_status

        def shares():
            student_shares = False
            # if the student's privacy is floor and the requesting user is on their floor
            if(self.get_object().privacy == 'floor') and onFloor():
                student_shares = True
Daniel W Bond's avatar
Daniel W Bond committed
136
137
            # if the student's privacy is building and the requesting users is
            # on their floor or in their building
Daniel W Bond's avatar
Daniel W Bond committed
138
139
140
141
142
143
            elif(self.get_object().privacy == 'building') and inBuilding():
                student_shares = True
            # if the student's privacy is set to 'student'
            elif(self.get_object().privacy == 'students'):
                student_shares = True
            return student_shares
Daniel W Bond's avatar
Daniel W Bond committed
144

Daniel W Bond's avatar
Daniel W Bond committed
145
        context['shares'] = shares()
146
147
        context['same_floor'] = same_floor
        context['has_flagged'] = bool(flags)
Daniel W Bond's avatar
Daniel W Bond committed
148
149
        if flags:
            context['my_flag'] = my_flag
Daniel W Bond's avatar
Daniel W Bond committed
150
151
        return context

Daniel W Bond's avatar
Daniel W Bond committed
152

153
class DetailCurrentStudent(LoginRequiredMixin, DetailView):
154
155
156
157
158
    model = Student
    context_object_name = 'student'
    template_name = 'detailStudent.html'

    login_url = 'login'
159
160
161
162

    def get_object(self):
        return get_object_or_404(Student, pk=self.request.session['_auth_user_id'])

Daniel W Bond's avatar
Daniel W Bond committed
163

164
165
166
# changeable student settings
class DetailStudentSettings(LoginRequiredMixin, DetailView):
    model = Student
167
168
169
170
    context_object_name = 'student'
    template_name = 'studentSettings.html'

    login_url = 'login'
171

Daniel W Bond's avatar
Daniel W Bond committed
172

173
class DetailCurrentStudentSettings(LoginRequiredMixin, DetailView):
174
    model = Student
175
176
177
178
    context_object_name = 'student'
    template_name = 'studentSettings.html'

    login_url = 'login'
179
180
181

    def get_object(self):
        return get_object_or_404(Student, pk=self.request.session['_auth_user_id'])
Daniel W Bond's avatar
Daniel W Bond committed
182

183

184
# update a student, but FormView to allow name update on same page
185
class UpdateStudent(LoginRequiredMixin, FormValidMessageMixin, FormView):
186
    template_name = 'updateStudent.html'
187
    form_class = StudentUpdateForm
188
189
    login_url = 'login'

190
191
    form_valid_message = "Your profile was successfully updated!"

192
193
194
195
196
197
198
199
200
201
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]

        if not(url_uname == self.request.user.username):
            return HttpResponseForbidden()
        else:
            return super(UpdateStudent, self).get(request, *args, **kwargs)

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
    def get_context_data(self, **kwargs):
        context = super(UpdateStudent, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)

        def pk_or_none(me, obj):
            if obj is None:
                return None
            else:
                return obj.pk

        form = StudentUpdateForm(initial={'first_name': me.user.first_name,
                                        'last_name': me.user.last_name,
                                        'gender': me.gender,
                                        'room': pk_or_none(me, me.room),
                                        'privacy': me.privacy,
218
219
                                        'major': pk_or_none(me, me.major),
                                        'graduating_year' : me.graduating_year,})
220
221
222
223

        if me.recent_changes() >= 2:
            form.fields['room'].widget = HiddenInput()

224
225
226
227
228
229
        context['my_form'] = form
        return context

    def form_valid(self, form):
        me = Student.objects.get(user=self.request.user)

230
231
232
233
234
235
236
237
238
        current_room = me.room
        try:
            form_room = Room.objects.get(pk=form.data['room'])
        except:
            form_room = None

        if current_room != form_room:
            me.times_changed_room += 1

239
240
241
        me.user.first_name = form.data['first_name']
        me.user.last_name = form.data['last_name']
        me.gender = form.data.getlist('gender')
242
        me.room = form_room
243
244
        me.privacy = form.data['privacy']
        me.major = Major.objects.get(pk=form.data['major'])
245
246
        me.graduating_year = form.data['graduating_year']

247
248
249
250
251
252
253
254
        me.user.save()
        me.save()

        return super(UpdateStudent, self).form_valid(form)

    def get_success_url(self):
        return reverse('detail_student',
                       kwargs={'slug':self.request.user.username})
255

256
257

    @ratelimit(key='user', rate='5/m', method='POST', block=True)
258
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
259
260
261
262
    def post(self, request, *args, **kwargs):
        return super(UpdateStudent, self).post(request, *args, **kwargs)


263
264
# welcome pages
class WelcomeName(LoginRequiredMixin, FormView):
265
    template_name = 'welcome_name.html'
266
267
268
    form_class = WelcomeNameForm
    login_url = 'login'

269
270
271
272
273
274
275
276
277
278
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]

        if not(url_uname == self.request.user.username):
            return HttpResponseForbidden()
        else:
            return super(WelcomeName, self).get(request, *args, **kwargs)

Daniel W Bond's avatar
Daniel W Bond committed
279
280
281
282
283
284
285
286
287
288
    def get_context_data(self, **kwargs):
        context = super(WelcomeName, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)

        form = WelcomeNameForm(initial={'first_name': me.user.first_name,
                                        'last_name': me.user.last_name,
                                        'gender': me.gender, })
        context['my_form'] = form
        return context
289

290
    def form_valid(self, form):
Daniel W Bond's avatar
Daniel W Bond committed
291
        me = Student.objects.get(user=self.request.user)
292

Daniel W Bond's avatar
Daniel W Bond committed
293
294
295
296
297
298
299
        me.user.first_name = form.data['first_name']
        me.user.last_name = form.data['last_name']

        me.gender = form.data.getlist('gender')

        me.completedName = True

300
        # wow... these calls actually work... >_______>
Daniel W Bond's avatar
Daniel W Bond committed
301
302
        me.user.save()
        me.save()
303
304
305

        return super(WelcomeName, self).form_valid(form)

306
307
308
309
    def get_success_url(self):
        return reverse('welcomePrivacy',
                       kwargs={'slug':self.request.user.username})

310
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
311
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
312
313
314
    def post(self, request, *args, **kwargs):
        return super(WelcomeName, self).post(request, *args, **kwargs)

315
316
317
318
319

class WelcomePrivacy(LoginRequiredMixin, UpdateView):
    model = Student
    fields = ['room', 'privacy', ]
    context_object_name = 'student'
320
    template_name = 'welcome_privacy.html'
321
322
323

    login_url = 'login'

324
325
326
327
328
329
330
331
332
333
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]

        if not(url_uname == self.request.user.username):
            return HttpResponseForbidden()
        else:
            return super(WelcomePrivacy, self).get(request, *args, **kwargs)

334
335
336
337
338
339
340
341
342
343
344
345
346
    def get_context_data(self, **kwargs):
        context = super(WelcomePrivacy, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)

        form = WelcomePrivacyForm()

        if me.recent_changes() >= 2:
            form.fields['room'].widget = HiddenInput()

        context['my_form'] = form
        return context

347
    def form_valid(self, form):
348
        # except that for some reason these fields no longer fill with their existant values
349
350
        self.obj = self.get_object()

351
352
353
354
355
356
357
358
359
        current_room = self.obj.room
        try:
            form_room = Room.objects.get(pk=form.data['room'])
        except:
            form_room = None

        if current_room != form_room:
            self.obj.times_changed_room += 1

360
        self.obj.completedPrivacy = True
361
        # this doesn't work for some magical reason
362
363
364
365
        self.obj.save()

        return super(WelcomePrivacy, self).form_valid(form)

366
367
368
369
    def get_success_url(self):
        return reverse('welcomeMajor',
                       kwargs={'slug':self.request.user.username})

370
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
371
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
372
373
374
    def post(self, request, *args, **kwargs):
        return super(WelcomePrivacy, self).post(request, *args, **kwargs)

375
376
377

class WelcomeMajor(LoginRequiredMixin, UpdateView):
    model = Student
378
    fields = ['major', 'graduating_year', ]
379
    context_object_name = 'student'
380
    template_name = 'welcome_major.html'
381
382
383

    login_url = 'login'

384
385
386
387
388
389
390
391
392
393
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]

        if not(url_uname == self.request.user.username):
            return HttpResponseForbidden()
        else:
            return super(WelcomeMajor, self).get(request, *args, **kwargs)

394
395
396
    def form_valid(self, form):
        self.obj = self.get_object()

397
        # this doesn't work for some reason
398
399
400
401
402
        self.obj.completedMajor = True
        self.obj.save()

        return super(WelcomeMajor, self).form_valid(form)

403
404
405
406
    def get_success_url(self):
        return reverse('welcomeSocial',
                       kwargs={'slug':self.request.user.username})

407
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
408
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
409
410
411
    def post(self, request, *args, **kwargs):
        return super(WelcomeMajor, self).post(request, *args, **kwargs)

412

413
414
# this is a work-in-progress catastrophuck
class WelcomeSocial(LoginRequiredMixin, FormValidMessageMixin, UpdateView):
415
416
    model = Student
    context_object_name = 'student'
417
    fields = ['completedSocial']
418
    template_name = 'welcome_social.html'
419
420
421

    login_url = 'login'

422
    form_valid_message = "You successfully finished the welcome walkthrough!"
423

424
425
426
427
428
429
430
431
432
433
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]

        if not(url_uname == self.request.user.username):
            return HttpResponseForbidden()
        else:
            return super(WelcomeSocial, self).get(request, *args, **kwargs)

434
435
436
437
438
439
440
441
    def form_valid(self, form):
        self.obj = self.get_object()

        self.obj.completedSocial = True
        self.obj.save()

        return super(WelcomeSocial, self).form_valid(form)

442
    # doesn't get called because it's not actually a form...
443
444
445
446
    def get_success_url(self):
        return reverse('detail_student',
                       kwargs={'slug':self.request.user.username})

447
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
448
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
449
450
451
    def post(self, request, *args, **kwargs):
        return super(UpdateStudent, self).post(request, *args, **kwargs)

452
453

# majors pages
Daniel W Bond's avatar
Daniel W Bond committed
454
455
456
457
458
459
class ListMajors(LoginRequiredMixin, ListView):
    model = Major
    queryset = Major.objects.all().order_by('name')
    context_object_name = 'majors'
    template_name = 'list_majors.html'

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
    login_url = 'login'


class DetailMajor(LoginRequiredMixin, DetailView):
    model = Major
    context_object_name = 'major'
    template_name = 'detail_major.html'

    login_url = 'login'

    def get_context_data(self, **kwargs):
        context = super(DetailMajor, self).get_context_data(**kwargs)
        me = Student.objects.get(user=self.request.user)

        students = Student.objects.filter(major=self.get_object()).order_by('room__floor__building__name', 'user__last_name', 'user__first_name')

        def onFloor(me, student):
            floor_status = False
            if me.get_floor() == student.get_floor():
                floor_status = True
            return floor_status

        def inBuilding(me, student):
            floor_status = False
            if me.get_building() == student.get_building():
                floor_status = True
            return floor_status

        aq_location_visible = []
        ra_location_visible = []
        sh_location_visible = []
        location_hidden = []

        aq_students = students.filter(room__floor__building__neighbourhood='aq')

        for student in aq_students:
            if student.privacy == u'students':
                aq_location_visible.append(student)
            elif (student.privacy == u'building') and inBuilding(me, student):
                aq_location_visible.append(student)
            elif (student.privacy == u'floor') and onFloor(me, student):
                aq_location_visible.append(student)
            else:
                location_hidden.append(student)

        ra_students = students.filter(room__floor__building__neighbourhood='ra')

        for student in ra_students:
            if student.privacy == u'students':
                ra_location_visible.append(student)
            elif (student.privacy == u'building') and inBuilding(me, student):
                ra_location_visible.append(student)
            elif (student.privacy == u'floor') and onFloor(me, student):
                ra_location_visible.append(student)
            else:
                location_hidden.append(student)

        sh_students = students.filter(room__floor__building__neighbourhood='sh')

        for student in sh_students:
            if student.privacy == u'students':
                sh_location_visible.append(student)
            elif (student.privacy == u'building') and inBuilding(me, student):
                sh_location_visible.append(student)
            elif (student.privacy == u'floor') and onFloor(me, student):
                sh_location_visible.append(student)
            else:
                location_hidden.append(student)

        context['aq_location_visible'] = aq_location_visible
        context['ra_location_visible'] = ra_location_visible
        context['sh_location_visible'] = sh_location_visible
        context['location_hidden'] = location_hidden

        return context
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


class CreateConfirmation(LoginRequiredMixin, CreateView):
    model = Confirmation
    fields = []
    template_name = 'create_confirmation.html'

    login_url = 'login'

    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        # [u'', u'accounts', u'student', u'gmason', u'flag', u'']
        url_uname = current_url.split('/')[3]

        confirmer = Student.objects.get(user=self.request.user)
        student = Student.objects.get(slug=url_uname)

        flags = Confirmation.objects.filter(confirmer=confirmer,
                                            student=student).count()

        # you can't flag yourself
        if confirmer == student:
            return HttpResponseForbidden()

        # check that the confirmer is on the floor of the student
        if not on_the_same_floor(student, confirmer):
            return HttpResponseForbidden()

        # check if the confirmer has already flagged the student
        if flags >= 1:
            return HttpResponseForbidden()

        return super(CreateConfirmation, self).get(request, *args, **kwargs)


    def get_context_data(self, **kwargs):
        context = super(CreateConfirmation, self).get_context_data(**kwargs)

        # duplicated code
        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]

        student = Student.objects.get(slug=url_uname)

        context['student'] = student

        return context

    def form_valid(self, form):

        # duplicated code
        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]

        confirmer = Student.objects.get(user=self.request.user)
        student = Student.objects.get(slug=url_uname)

        form.instance.confirmer = confirmer
        form.instance.student = student

        return super(CreateConfirmation, self).form_valid(form)

    @ratelimit(key='user', rate='10/m', method='POST', block=True)
    @ratelimit(key='user', rate='50/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(CreateConfirmation, self).post(request, *args, **kwargs)

    def get_success_url(self):
        # redirect to the flagged student page when saving
        return reverse('detail_student',
                       kwargs={'slug':self.object.student.slug})


class DeleteConfirmation(LoginRequiredMixin, DeleteView):
    model = Confirmation
Daniel W Bond's avatar
Daniel W Bond committed
611
    template_name = 'delete_confirmation.html'
612
613
614

    login_url = 'login'

Daniel W Bond's avatar
Daniel W Bond committed
615
616
617
    def get(self, request, *args, **kwargs):
        requester = Student.objects.get(user=self.request.user)
        confirmer = self.get_object().confirmer
618

Daniel W Bond's avatar
Daniel W Bond committed
619
620
621
622
        if not(requester == confirmer):
            return HttpResponseForbidden()
        else:
            return super(DeleteConfirmation, self).get(request, *args, **kwargs)
623
624
625

    def get_success_url(self):
        return reverse('detail_student',
Daniel W Bond's avatar
Daniel W Bond committed
626
                       kwargs={'slug':self.object.student.slug})