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

Daniel W Bond's avatar
Daniel W Bond committed
24

25
26
settings_redirect = """You've already finished the welcome walkthrough.
                       Your user settings can now be changed here on this page."""
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
#########

bug_reporting = """Welcome back to SRCT Roomlist. This project is the
                   <a href="https://srct.gmu.edu/projects/">collaborative work
                   of students like you</a>. If you see anything amiss, or have ideas for
                   features or a better user experience, please send an email to
                   roomlist@lists.srct.gmu.edu, tweet
                   <a href="https://twitter.com/MasonSRCT/">@MasonSRCT</a>, or, for the
                   more technically experienced, review our
                   <a href="https://git.gmu.edu/srct/roomlist/issues">issues page</a>."""

privacy_reminder = """Welcome back to SRCT Roomlist. A friendly reminder you can change
                      your privacy settings at any time on your settings page by
                      clicking the cog in the upper right of your screen."""

disclaimer = """Welcome back to SRCT Roomlist. Just to be perfectly clear, this project
                is provided as a service by the
                <a href="https://gmu.collegiatelink.net/organization/srct">registered
                student organization</a>
                <a href="https://srct.gmu.edu/">Student-Run Computing and Technology</a>.
                We are not a part of <a href="http://housing.gmu.edu/">Mason Housing</a>:
                all information is voluntarily provided by participating students."""

whatsopen_plug = """Welcome back to SRCT Roomlist. Wondering what's open at this hour?
                    Check out another one of our
                    <a href="https://srct.gmu.edu/projects/">student-built and hosted</a>
                    projects: <a href="https://whatsopen.gmu.edu/">whatsopen.gmu.edu</a>."""

open_source = """Welcome back to SRCT Roomlist. For the curious at heart,
                 <a href="http://www.gnu.org/philosophy/free-sw.en.html">you can always
                 review</a> this project's
                 <a href="https://git.gmu.edu/srct/roomlist/tree/master">source code</a>.
                 Come <a href="https://srct.gmu.edu/">to a meeting</a> and learn how to
                 contribute!"""

return_messages = [bug_reporting, privacy_reminder, disclaimer, whatsopen_plug, open_source]

65
66
67
68

def custom_cas_login(request, *args, **kwargs):
    response = cas_login(request, *args, **kwargs)
    # returns HttpResponseRedirect
69

70
71
    if request.user.is_authenticated():

72
73
74
75
76
77
78
79
80
81
82
83
84
85
        if not request.user.student.totally_done():

            if not request.user.student.completedName:
                return HttpResponseRedirect(reverse('welcomeName',
                                            kwargs={'slug':request.user.username}))
            elif not request.user.student.completedPrivacy:
                return HttpResponseRedirect(reverse('welcomePrivacy',
                                            kwargs={'slug':request.user.username}))
            elif not request.user.student.completedMajor:
                return HttpResponseRedirect(reverse('welcomeMajor',
                                            kwargs={'slug':request.user.username}))
            elif not request.user.completedSocial:
                return HttpResponseRedirect(reverse('welcomeSocial',
                                            kwargs={'slug':request.user.username}))
86
87
88
        else:
            welcome_back = random.choice(return_messages)
            messages.add_message(request, messages.INFO, mark_safe(welcome_back))
89
90
91
92

    return response


93
94
def on_the_same_floor(student, confirmer):
    if student == confirmer:
95
        # Student is confirmer
96
97
98
99
100
        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):
101
        # one Student is None
102
103
        return False
    elif not(student_floor == confirmer_floor):
104
        # not the same floor
105
106
107
108
109
        return False
    else:
        return True


110
111
112
113
114
115
def pk_or_none(me, obj):
    if obj is None:
        return None
    else:
        return obj.pk

116

117
118
119
# details about the student
class DetailStudent(LoginRequiredMixin, DetailView):
    model = Student
120
121
122
123
    context_object_name = 'student'
    template_name = 'detailStudent.html'

    login_url = 'login'
Daniel W Bond's avatar
Daniel W Bond committed
124
125
126
127

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

128
        requesting_student = Student.objects.get(user=self.request.user)
Daniel W Bond's avatar
Daniel W Bond committed
129

130
131
132
133
134
        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
135
136
137
138
139
        if flags:
            try:
                my_flag = Confirmation.objects.get(confirmer=requesting_student,
                                                   student=self.get_object())
            except Exception as e:
140
141
                print("Students are not supposed to be able to make more than one flag per student.")
                print(e)
142

Daniel W Bond's avatar
Daniel W Bond committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        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
160
161
            # 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
162
163
164
165
166
167
            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
168

Daniel W Bond's avatar
Daniel W Bond committed
169
        context['shares'] = shares()
170
171
        context['same_floor'] = same_floor
        context['has_flagged'] = bool(flags)
Daniel W Bond's avatar
Daniel W Bond committed
172
173
        if flags:
            context['my_flag'] = my_flag
Daniel W Bond's avatar
Daniel W Bond committed
174
175
        return context

Daniel W Bond's avatar
Daniel W Bond committed
176

177
class DetailCurrentStudent(LoginRequiredMixin, DetailView):
178
179
180
181
182
    model = Student
    context_object_name = 'student'
    template_name = 'detailStudent.html'

    login_url = 'login'
183
184
185
186

    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
187

188
189
190
# changeable student settings
class DetailStudentSettings(LoginRequiredMixin, DetailView):
    model = Student
191
192
193
194
    context_object_name = 'student'
    template_name = 'studentSettings.html'

    login_url = 'login'
195

Daniel W Bond's avatar
Daniel W Bond committed
196

197
class DetailCurrentStudentSettings(LoginRequiredMixin, DetailView):
198
    model = Student
199
200
201
202
    context_object_name = 'student'
    template_name = 'studentSettings.html'

    login_url = 'login'
203
204
205

    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
206

207
# update a student, but FormView to allow name update on same page
208
class UpdateStudent(LoginRequiredMixin, FormValidMessageMixin, FormView):
209
    template_name = 'updateStudent.html'
210
    form_class = StudentUpdateForm
211
212
    login_url = 'login'

213
214
    form_valid_message = "Your profile was successfully updated!"

215
216
217
218
219
220
221
222
223
224
    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)

225
226
227
228
229
230
    def get_context_data(self, **kwargs):
        context = super(UpdateStudent, self).get_context_data(**kwargs)

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

        form = StudentUpdateForm(initial={'first_name': me.user.first_name,
231
232
                                          'last_name': me.user.last_name,
                                          'gender': me.gender,
233
                                          'show_gender': me.show_gender,
234
235
236
                                          'room': pk_or_none(me, me.room),
                                          'privacy': me.privacy,
                                          'major': pk_or_none(me, me.major),
237
238
                                          'graduating_year': me.graduating_year,
                                          'on_campus': me.on_campus, })
239

240
        if me.recent_changes() > 2:
241
            form.fields['room'].widget = HiddenInput()
242
243
            form.fields['privacy'].widget = HiddenInput()
            form.fields['on_campus'].widget = HiddenInput()
244
245
        else:
            form.fields['room'].widget.user = self.request.user
246

247
248
249
250
251
        # bootstrap
        form.fields['first_name'].widget.attrs['class'] = 'form-control'
        form.fields['last_name'].widget.attrs['class'] = 'form-control'
        form.fields['graduating_year'].widget.attrs['class'] = 'form-control'

252
        context['my_form'] = form
Daniel W Bond's avatar
Daniel W Bond committed
253

254
255
        return context

Daniel W Bond's avatar
Daniel W Bond committed
256
257
258
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
259
260
        #for key, value in request.POST.iteritems():
            #print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
261
262
        return super(UpdateStudent, self).post(request, *args, **kwargs)

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

266
        #print("In form valid method!")
Daniel W Bond's avatar
Daniel W Bond committed
267

268
269
        #for key, value in form.data.iteritems():
            #print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
270

271
        current_room = me.room
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

        # if you somehow got around the hidden widget, you're still outta luck
        if me.recent_changes() > 2:
            form_room = current_room
        else:
            try:
                form_room = Room.objects.get(pk=form.data['room'])
            except:
                form_room = None

        # casts to an integer, 0 or 1
        on_campus = strtobool(form.data.get('on_campus', 'True'))

        # no room if you move off campus
        if not on_campus:
287
288
            form_room = None

289
        # note this is after the 'on campus' check
290
291
        if current_room != form_room:
            me.times_changed_room += 1
292
            Confirmation.objects.filter(student=me).delete()
293

294
        me.on_campus = on_campus
295
296
297
298
299
300
301
        me.room = form_room

        try:
            me.major = Major.objects.get(pk=form.data['major'])
        except:
            me.major = None

302
303
304
        me.user.first_name = form.data['first_name']
        me.user.last_name = form.data['last_name']
        me.gender = form.data.getlist('gender')
305
        me.show_gender = strtobool(form.data.get('show_gender', 'False'))
306
        me.privacy = form.data['privacy']
307
308
        me.graduating_year = form.data['graduating_year']

309
310
311
312
313
314
        me.user.save()
        me.save()

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

    def get_success_url(self):
315
316
317
318
319

        if self.request.user.student.recent_changes() == 2:

            messages.add_message(self.request, messages.WARNING, 'To safeguard everyone\'s privacy, you have just one remaining room change for the semester before you\'ll need to send us an email at roomlist@lists.srct.gmu.edu.')

320
321
        return reverse('detail_student',
                       kwargs={'slug':self.request.user.username})
322

323

324
325
# welcome pages
class WelcomeName(LoginRequiredMixin, FormView):
326
    template_name = 'welcome_name.html'
327
328
329
    form_class = WelcomeNameForm
    login_url = 'login'

330
331
332
333
334
335
336
    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()
337
338
339
340
        elif self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
            return reverse('updateStudent',
                           kwargs={'slug':self.request.user.username})
341
342
343
        else:
            return super(WelcomeName, self).get(request, *args, **kwargs)

344
345


Daniel W Bond's avatar
Daniel W Bond committed
346
347
348
349
350
351
352
    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,
353
354
                                        'gender': me.gender,
                                        'show_gender': me.show_gender, })
355
356
357
358

        form.fields['first_name'].widget.attrs['class'] = 'form-control'
        form.fields['last_name'].widget.attrs['class'] = 'form-control'

Daniel W Bond's avatar
Daniel W Bond committed
359
360
        context['my_form'] = form
        return context
361

362
363
364
365
366
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(WelcomeName, self).post(request, *args, **kwargs)

367
    def form_valid(self, form):
Daniel W Bond's avatar
Daniel W Bond committed
368
        me = Student.objects.get(user=self.request.user)
369

Daniel W Bond's avatar
Daniel W Bond committed
370
371
372
373
        me.user.first_name = form.data['first_name']
        me.user.last_name = form.data['last_name']

        me.gender = form.data.getlist('gender')
374
        me.show_gender = strtobool(form.data.get('show_gender', 'False'))
Daniel W Bond's avatar
Daniel W Bond committed
375
376
377
378
379

        me.completedName = True

        me.user.save()
        me.save()
380
381
382

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

383
384
385
386
    def get_success_url(self):
        return reverse('welcomePrivacy',
                       kwargs={'slug':self.request.user.username})

387
388
389

class WelcomePrivacy(LoginRequiredMixin, UpdateView):
    model = Student
Daniel W Bond's avatar
Daniel W Bond committed
390
    form_class = WelcomePrivacyForm
391
    context_object_name = 'student'
392
    template_name = 'welcome_privacy.html'
393
394
395

    login_url = 'login'

396
397
398
399
400
401
402
    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()
403
404
405
406
        elif self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
            return reverse('updateStudent',
                           kwargs={'slug':self.request.user.username})
407
408
409
        else:
            return super(WelcomePrivacy, self).get(request, *args, **kwargs)

410
411
412
413
414
415
416
417
418
    def get_context_data(self, **kwargs):
        context = super(WelcomePrivacy, self).get_context_data(**kwargs)

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

        form = WelcomePrivacyForm()

        form.fields['room'].widget.user = self.request.user

419
420
        form.fields['on_campus'].initial = self.request.user.student.on_campus

421
422
423
424
425
426
427
428
429
        context['my_form'] = form

        return context

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

Daniel W Bond's avatar
Daniel W Bond committed
430
431
    def form_valid(self, form):
        me = self.get_object()
432

Daniel W Bond's avatar
Daniel W Bond committed
433
        current_room = me.room
434

435
436
437
438
439
440
441
442
443
444
445
446
447
448
        # if you somehow got around the hidden widget, you're still outta luck
        if me.recent_changes() > 2:
            form_room = current_room
        else:
            try:
                form_room = Room.objects.get(pk=form.data['room'])
            except:
                form_room = None

        # casts to an integer, 0 or 1
        on_campus = strtobool(form.data.get('on_campus', 'True'))

        # no room if you move off campus
        if not on_campus:
Daniel W Bond's avatar
Daniel W Bond committed
449
            form_room = None
450

Daniel W Bond's avatar
Daniel W Bond committed
451
452
        if current_room != form_room:
            form.instance.times_changed_room += 1
453
            Confirmation.objects.filter(student=me).delete()
454

Daniel W Bond's avatar
Daniel W Bond committed
455
        form.instance.completedPrivacy = True
456

457
458
459
        form.instance.on_campus = on_campus
        form.instance.room = form_room

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

462
463
464
465
    def get_success_url(self):
        return reverse('welcomeMajor',
                       kwargs={'slug':self.request.user.username})

466
467
468

class WelcomeMajor(LoginRequiredMixin, UpdateView):
    model = Student
469
    fields = ['major', 'graduating_year', ]
470
    context_object_name = 'student'
471
    template_name = 'welcome_major.html'
472
473
474

    login_url = 'login'

475
476
477
478
479
480
481
    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()
482
483
484
485
        elif self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
            return reverse('updateStudent',
                           kwargs={'slug':self.request.user.username})
486
487
488
        else:
            return super(WelcomeMajor, self).get(request, *args, **kwargs)

489
490
491
492
493
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(WelcomeMajor, self).post(request, *args, **kwargs)

494
495
    def form_valid(self, form):

Daniel W Bond's avatar
Daniel W Bond committed
496
        form.instance.completedMajor = True
497
498
499

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

500
501
502
503
    def get_success_url(self):
        return reverse('welcomeSocial',
                       kwargs={'slug':self.request.user.username})

504

505
class WelcomeSocial(LoginRequiredMixin, UpdateView):
506
    model = Student
Daniel W Bond's avatar
Daniel W Bond committed
507
    form_class = WelcomeSocialForm
508
    context_object_name = 'student'
509
    template_name = 'welcome_social.html'
510
511
    login_url = 'login'

512
513
514
515
516
517
518
    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()
519
520
521
522
        elif self.request.user.student.totally_done():
            messages.add_message(request, messages.INFO, settings_redirect)
            return reverse('updateStudent',
                           kwargs={'slug':self.request.user.username})
523
524
525
        else:
            return super(WelcomeSocial, self).get(request, *args, **kwargs)

526
527
528
529
530
    @ratelimit(key='user', rate='5/m', method='POST', block=True)
    @ratelimit(key='user', rate='10/d', method='POST', block=True)
    def post(self, request, *args, **kwargs):
        return super(WelcomeSocial, self).post(request, *args, **kwargs)

531
532
    def form_valid(self, form):

Daniel W Bond's avatar
Daniel W Bond committed
533
        form.instance.completedSocial = True
534
535
536

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

537
    def get_success_url(self):
538
539
540
541
542

        if self.request.user.student.totally_done():
            messages.add_message(self.request, messages.SUCCESS,
                                 "You successfully finished the welcome walkthrough!")

543
544
545
        return reverse('detail_student',
                       kwargs={'slug':self.request.user.username})

546
547

# majors pages
Daniel W Bond's avatar
Daniel W Bond committed
548
549
550
551
552
553
class ListMajors(LoginRequiredMixin, ListView):
    model = Major
    queryset = Major.objects.all().order_by('name')
    context_object_name = 'majors'
    template_name = 'list_majors.html'

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


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

678
679
680
681
682
    @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)

683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
    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)

    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
705
    template_name = 'delete_confirmation.html'
706
707
708

    login_url = 'login'

Daniel W Bond's avatar
Daniel W Bond committed
709
710
711
    def get(self, request, *args, **kwargs):
        requester = Student.objects.get(user=self.request.user)
        confirmer = self.get_object().confirmer
712

Daniel W Bond's avatar
Daniel W Bond committed
713
714
715
716
        if not(requester == confirmer):
            return HttpResponseForbidden()
        else:
            return super(DeleteConfirmation, self).get(request, *args, **kwargs)
717
718
719

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