views.py 20.5 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
6
from collections import OrderedDict
from itertools import groupby
7
import re
8
# core django imports
9
from django.http import HttpResponseForbidden, HttpResponseRedirect, Http404
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
10
from django.views.generic import CreateView, ListView, DetailView, FormView, DeleteView
11
from django.core.urlresolvers import reverse
12
13
from django.contrib import messages
from django.utils.safestring import mark_safe
14
from django.forms.widgets import HiddenInput
15
16
17
18
from django.conf import settings
from django.template.loader import get_template
from django.core.mail import EmailMultiAlternatives, get_connection
from django.template import Context
19
from django.core.exceptions import ObjectDoesNotExist
20
# third party imports
21
from braces.views import LoginRequiredMixin, FormValidMessageMixin
22
from cas.views import login as cas_login
23
from ratelimit.decorators import ratelimit
24
# imports from your apps
Daniel W Bond's avatar
Daniel W Bond committed
25
from .models import Student, Major, Confirmation
26
from .forms import StudentUpdateForm, FarewellFeedbackForm
27
from housing.models import Room
28
from core.utils import shadowbanning, on_the_same_floor, pk_or_none, create_email, no_nums
29
30


31
32
33
# details about the student
class DetailStudent(LoginRequiredMixin, DetailView):
    model = Student
34
    context_object_name = 'student'
Daniel W Bond's avatar
Daniel W Bond committed
35
    template_name = 'detail_student.html'
36
37

    login_url = 'login'
Daniel W Bond's avatar
Daniel W Bond committed
38

39
40
41
42
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]
43
44
45
46
        try:
            detailed_student = Student.objects.get(user__username=url_uname)
        except ObjectDoesNotExist:
            raise Http404
47
48
49
50
51
52

        if (detailed_student in self.request.user.student.blocked_kids.all()):
            raise Http404
        else:
            return super(DetailStudent, self).get(request, *args, **kwargs)

Daniel W Bond's avatar
Daniel W Bond committed
53
54
55
    def get_context_data(self, **kwargs):
        context = super(DetailStudent, self).get_context_data(**kwargs)

56
        requesting_student = self.request.user.student
Daniel W Bond's avatar
Daniel W Bond committed
57

58
59
60
61
62
        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
63
64
65
66
67
        if flags:
            try:
                my_flag = Confirmation.objects.get(confirmer=requesting_student,
                                                   student=self.get_object())
            except Exception as e:
68
69
                print("Students are not supposed to be able to make more than one flag per student.")
                print(e)
70

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
71
        # recognizably too complex
Daniel W Bond's avatar
Daniel W Bond committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        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
89
90
            # 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
91
92
93
94
95
96
            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
97

Daniel W Bond's avatar
Daniel W Bond committed
98
        context['shares'] = shares()
99
100
        context['same_floor'] = same_floor
        context['has_flagged'] = bool(flags)
Daniel W Bond's avatar
Daniel W Bond committed
101
102
        if flags:
            context['my_flag'] = my_flag
Daniel W Bond's avatar
Daniel W Bond committed
103
104
        return context

Daniel W Bond's avatar
Daniel W Bond committed
105

106
# update a student, but FormView to allow name update on same page
107
class UpdateStudent(LoginRequiredMixin, FormValidMessageMixin, FormView):
108
    template_name = 'update_student.html'
109
    form_class = StudentUpdateForm
110
111
    login_url = 'login'

112
113
    form_valid_message = "Your profile was successfully updated!"

114
115
116
117
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]
118
119
120
121
        try:
            student = Student.objects.get(user__username=url_uname)
        except ObjectDoesNotExist:
            raise Http404
122
123

        if not(url_uname == self.request.user.username):
124
125
            return HttpResponseRedirect(reverse('update_student',
                                                kwargs={'slug': self.request.user.username}))
126
127
128
        else:
            return super(UpdateStudent, self).get(request, *args, **kwargs)

129
130
131
    def get_context_data(self, **kwargs):
        context = super(UpdateStudent, self).get_context_data(**kwargs)

132
        me = self.request.user.student
133
        majors = [pk_or_none(me, major) for major in me.major.all()]
134
135

        form = StudentUpdateForm(initial={'first_name': me.user.first_name,
136
137
                                          'last_name': me.user.last_name,
                                          'gender': me.gender,
138
                                          'show_gender': me.show_gender,
139
140
                                          'room': pk_or_none(me, me.room),
                                          'privacy': me.privacy,
141
                                          'blocked_kids': me.blocked_kids.all(),
142
                                          'major': majors,
143
144
                                          'graduating_year': me.graduating_year,
                                          'on_campus': me.on_campus, })
145

146
        form.fields['blocked_kids'].queryset = Student.objects.exclude(user=self.request.user)
147

148
        if me.recent_changes() > 2:
149
            form.fields['room'].widget = HiddenInput()
150
151
            form.fields['privacy'].widget = HiddenInput()
            form.fields['on_campus'].widget = HiddenInput()
152
153
        else:
            form.fields['room'].widget.user = self.request.user
154

155
156
157
158
        # RAs and RDs cannot move off campus
        if me.is_staff():
            form.fields['on_campus'].disabled = True

159
160
161
162
163
        # 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'

164
        # chosen
165
166
        form.fields['major'].widget.attrs['class'] = 'form-control chosen-select'
        form.fields['blocked_kids'].widget.attrs['class'] = 'form-control blocked-select'
167

168
        context['my_form'] = form
Daniel W Bond's avatar
Daniel W Bond committed
169

170
171
        return context

Daniel W Bond's avatar
Daniel W Bond committed
172
173
174
    @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):
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
175
        # for key, value in request.POST.iteritems():
176
        #     print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
177
178
        return super(UpdateStudent, self).post(request, *args, **kwargs)

179
    def form_valid(self, form):
180
        me = self.request.user.student
181

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
182
        # print("In form valid method!")
Daniel W Bond's avatar
Daniel W Bond committed
183

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
184
        # for key, value in form.data.iteritems():
185
        #     print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
186

187
        current_room = me.room
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202

        # 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:
203
204
            form_room = None

205
        # note this is after the 'on campus' check
206
207
        if current_room != form_room:
            me.times_changed_room += 1
208
            Confirmation.objects.filter(student=me).delete()
209

210
        me.on_campus = on_campus
211
212
        me.room = form_room

213
214
215
216
217
218
219
        # if you don't live on campus you can't limit yourself to a nonexistent
        # floor or room
        if not(me.on_campus):
            me.privacy = 'students'
        else:
            me.privacy = form.data['privacy']

220
221
222
223
        # if you are an RA or an RD, you live on campus
        if me.is_staff():
            me.on_campus = True

224
        try:
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
            # in case someone disabled the js, limit processing to only the first
            # two majors passed by the user
            # we also eliminate the potential a student manipulates the form to
            # pass in two majors of the same type by casting to a set
            form_major_pks = set(form.data.getlist('major')[:2])
            # retrieve the major objects from the list of pk strings
            form_majors = [Major.objects.get(pk=pk) for pk in form_major_pks]
            # print(form_majors)
            # iterate over a student's current majors
            for current_major in me.major.all():
                # remove m2m relationship if not in majors from form
                if current_major not in form_majors:
                    me.major.remove(current_major)
            # iterate over the majors in the form
            for form_major in form_majors:
                # add new m2m relationship to student
                if form_major not in me.major.all():
                    me.major.add(form_major)
243
        except:
244
245
            # don't change majors
            pass
246

247
        # replicate the same thing for the other m2m field
248
        try:
249
250
251
            form_blocked_pks = set(form.data.getlist('blocked_kids'))
            current_blocked = me.blocked_kids.all()
            # most people will not being blocking other students
252
            if form_blocked_pks or current_blocked:
253
254
255
256
257
258
259
                form_blocked = [Student.objects.get(pk=pk) for pk in form_blocked_pks]
                for current_block in current_blocked:
                    if current_block not in form_blocked:
                        me.blocked_kids.remove(current_block)
                for form_block in form_blocked:
                    if form_block not in current_blocked:
                        me.blocked_kids.add(form_block)
260
        except:
261
            pass
262

263
264
        me.user.first_name = no_nums(form.data['first_name'])
        me.user.last_name = no_nums(form.data['last_name'])
265
        me.gender = form.data.getlist('gender')
266
        me.show_gender = strtobool(form.data.get('show_gender', 'False'))
267
        me.graduating_year = form.data['graduating_year']
268
269
270
271
272
273
        me.user.save()
        me.save()

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

    def get_success_url(self):
274
275
276
277
278

        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.')

279
        return reverse('detail_student',
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
280
                       kwargs={'slug': self.request.user.username})
281

282

283
284
285
class DeleteStudent(FormView):
    form_class = FarewellFeedbackForm
    template_name = 'delete_student.html'
286

287
288
289
290
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]
291
292
293
294
        try:
            student = Student.objects.get(user__username=url_uname)
        except ObjectDoesNotExist:
            raise Http404
295

296
297
298
299
300
301
302
303
304
        if student.is_staff():
            staff_msg = """To delete your account, contact us if you are no longer a
                           Resident Advisor or Director at
                           <a href="mailto:roomlist@lists.srct.gmu.edu">
                           roomlist@lists.srct.gmu.edu</a>."""
            messages.add_message(self.request, messages.ERROR, mark_safe(staff_msg))
            return HttpResponseRedirect(reverse('update_student',
                                                kwargs={'slug': self.request.user.username}))
        elif not(url_uname == self.request.user.username):
305
306
            return HttpResponseRedirect(reverse('delete_student',
                                                kwargs={'slug': self.request.user.username}))
307
        else:
308
            return super(DeleteStudent, self).get(request, *args, **kwargs)
309

310
    def get_context_data(self, **kwargs):
311
        context = super(DeleteStudent, self).get_context_data(**kwargs)
312

313
        me = self.request.user.student
314

315
        context['student'] = me
316
317
318

        return context

Daniel W Bond's avatar
Daniel W Bond committed
319
    def form_valid(self, form):
320
321
322
        user = self.request.user
        student = self.request.user.student

323
324
325
326
327
328
329
330
331
332
333
334
        # we're using this api because opening smtp connections is taxing in
        # that it takes time-- we want to send both emails at once without
        # having to log in and out and back in and out again
        connection = get_connection()

        # send email to the student
        text_path = 'email/farewell.txt'
        html_path = 'email/farewell.html'

        if form.cleaned_data['leaving']:
            context = {
                'student_name': student.get_first_name_or_uname,
335
                'special_message': "We're glad you gave our service a try."
336
            }
337
        else:
338
339
340
341
            context = {
                'student_name': student.get_first_name_or_uname,
                'special_message': "We wish you luck in your time after Mason!"
            }
342

343
344
        subject = "You successfully deleted your account on Roomlist"
        to = user.email
345

346
        student_email = create_email(text_path, html_path, subject, to, context)
347

348
349
350
351
        # send feedback to the admins if there is feedback to send
        if form.cleaned_data['feedback']:
            text_path = 'email/feedback.txt'
            html_path = 'email/feedback.html'
352

353
            date_text = student.created.strftime('%A, %B %d, %Y')
354

355
356
357
358
            if form.cleaned_data['leaving']:
                leaving = ""
            else:
                leaving = "not"
359

360
361
362
363
364
365
            context = {
                'student_name':  student.get_first_name_or_uname,
                'signup_date': date_text,
                'leaving': leaving,
                'feedback': form.cleaned_data['feedback']
            }
366

367
368
            subject = "Feedback from Roomlist account deletion"
            to = 'roomlist@lists.srct.gmu.edu'
369

370
            feedback_email = create_email(text_path, html_path, subject, to, context)
371

372
            connection.send_messages([student_email, feedback_email])
373
        else:
374
            connection.send_messages([student_email])
375

376
377
        # yes, we do have to manually close the connection
        connection.close()
378

379
380
381
382
383
        # delete both the student object and the student object
        confirmations = Confirmation.objects.filter(confirmer=student)
        if confirmations:
            for confirmation in confirmations:
                confirmation.delete()
384
385
        student.delete()
        user.delete()
386

387
        return super(DeleteStudent, self).form_valid(form)
388

389
    def get_success_url(self):
390
        return reverse('homepage')
391
392

# majors pages
393
class ListMajors(ListView):
Daniel W Bond's avatar
Daniel W Bond committed
394
395
396
397
398
    model = Major
    queryset = Major.objects.all().order_by('name')
    context_object_name = 'majors'
    template_name = 'list_majors.html'

399
400
401
402
403
404
405
406
407
408

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)
409
        me = self.request.user.student
410

411
412
        # all students in the major-- needs to be ordered for groupby
        major_students = Student.objects.filter(major__in=[self.get_object()]).order_by('graduating_year')
413

414
        students_by_year = OrderedDict()  # we're ordering from senior on down
415

416
417
418
419
        for year, students in groupby(major_students, lambda student: student.graduating_year):
            student_list = list(students)  # students without the casting is an iterator
            visible_students = shadowbanning(me, student_list)  # remove blocked students
            students_by_year[year] = visible_students  # remembers insertion order
420

421
        context['students_by_year'] = students_by_year
422
423

        return context
424
425
426


class CreateConfirmation(LoginRequiredMixin, CreateView):
427
428
429
    """Students on the same floor may flag one another.

    This is our attempt at crowdsourced verification."""
430
431
432
433
434
435
436
437
438
    model = Confirmation
    fields = []
    template_name = 'create_confirmation.html'

    login_url = 'login'

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

        current_url = self.request.get_full_path()
439
440
441
        # [u'', u'accounts', u'student', u'gmason', u'flag', u'confirmer']
        confirmer_uname = current_url.split('/')[3]
        student_uname = current_url.split('/')[5]
442
443
444
445
446
447
448
        try:
            confirmer = Student.objects.get(user__username=confirmer_uname)
            student = Student.objects.get(user__username=student_uname)
            flags = Confirmation.objects.filter(confirmer=confirmer,
                                                student=student).count()
        except ObjectDoesNotExist:
            raise Http404
449
450
451

        # you can't flag yourself
        if confirmer == student:
452
            raise Http404
453
454
455
456
457
458
459
460
461

        # 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()

462
463
464
        # you can't see the page if the person has banned you
        if confirmer in student.blocked_kids.all():
            raise Http404
465
466
467
468
469
470
471
472

        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()
473
        url_uname = current_url.split('/')[5]
474
475
476
477
478
479
480

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

        context['student'] = student

        return context

481
482
483
484
485
    @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)

486
487
488
489
    def form_valid(self, form):

        # duplicated code
        current_url = self.request.get_full_path()
490
        url_uname = current_url.split('/')[5]
491
492
493
494
495
496
497
498
499
500
501
502

        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',
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
503
                       kwargs={'slug': self.object.student.slug})
504
505
506
507


class DeleteConfirmation(LoginRequiredMixin, DeleteView):
    model = Confirmation
Daniel W Bond's avatar
Daniel W Bond committed
508
    template_name = 'delete_confirmation.html'
509
510
511

    login_url = 'login'

Daniel W Bond's avatar
Daniel W Bond committed
512
    def get(self, request, *args, **kwargs):
513
514
        requester = self.request.user.student

515
516
        current_url = self.request.get_full_path()
        confirmer_uname = current_url.split('/')[3]
517
        # not catching exceptions here; that's handled in get_object
Daniel W Bond's avatar
Daniel W Bond committed
518
        confirmer = Student.objects.get(user__username=confirmer_uname)
519

520
        # only the person who created the confirmation may delete it
Daniel W Bond's avatar
Daniel W Bond committed
521
522
        if not(requester == confirmer):
            return HttpResponseForbidden()
523
        # however, if the confirmation just flat out doesn't exist...
Daniel W Bond's avatar
Daniel W Bond committed
524
        else:
525
526
527
528
529
530
            try:
                confirmer = self.get_object().confirmer
            except ObjectDoesNotExist:
                raise Http404
            else:
                return super(DeleteConfirmation, self).get(request, *args, **kwargs)
531

532
533
534
535
536
537
    def get_object(self):
        current_url = self.request.get_full_path()
        # [u'', u'accounts', u'student', u'gmason', u'flag', u'confirmer', delete]
        confirmer_uname = current_url.split('/')[3]
        student_uname = current_url.split('/')[5]

538
539
540
541
542
543
        try:
            confirmer = Student.objects.get(user__username=confirmer_uname)
            student = Student.objects.get(user__username=student_uname)
            confirmation = Confirmation.objects.get(confirmer=confirmer, student=student)
        except ObjectDoesNotExist:
            raise Http404
544
        return confirmation
545
546
547

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