views.py 19.7 KB
Newer Older
1
2
# standard library imports
from __future__ import absolute_import, print_function
3
from distutils.util import strtobool
4
5
from collections import OrderedDict
from itertools import groupby
6
# core django imports
7
from django.http import HttpResponseForbidden, HttpResponseRedirect, Http404
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
8
from django.views.generic import CreateView, ListView, DetailView, FormView, DeleteView
9
from django.core.urlresolvers import reverse
10
11
from django.contrib import messages
from django.utils.safestring import mark_safe
12
from django.forms.widgets import HiddenInput
Daniel W Bond's avatar
Daniel W Bond committed
13
from django.core.mail import get_connection
14
from django.core.exceptions import ObjectDoesNotExist
15
# third party imports
16
from braces.views import LoginRequiredMixin, FormValidMessageMixin
17
from ratelimit.decorators import ratelimit
18
# imports from your apps
Daniel W Bond's avatar
Daniel W Bond committed
19
from .models import Student, Major, Confirmation
20
from .forms import StudentUpdateForm, FarewellFeedbackForm
21
from housing.models import Room
22
23
from core.utils import (shadowbanning, on_the_same_floor, pk_or_none, create_email,
                        no_nums)
24
from core.views import StudentContextMixin
25
26


27
28
29
# details about the student
class DetailStudent(LoginRequiredMixin, DetailView):
    model = Student
30
    context_object_name = 'student'
Daniel W Bond's avatar
Daniel W Bond committed
31
    template_name = 'detail_student.html'
32
33

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

35
36
37
38
    def get(self, request, *args, **kwargs):

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

        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
49
50
51
    def get_context_data(self, **kwargs):
        context = super(DetailStudent, self).get_context_data(**kwargs)

52
        requesting_student = self.request.user.student
Daniel W Bond's avatar
Daniel W Bond committed
53

54
55
56
57
58
        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
59
60
61
62
        if flags:
            try:
                my_flag = Confirmation.objects.get(confirmer=requesting_student,
                                                   student=self.get_object())
63
            # students are not supposed to be able to make more than one flag per student
Daniel W Bond's avatar
Daniel W Bond committed
64
            except Exception as e:
65
                print(e)
66

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

Daniel W Bond's avatar
Daniel W Bond committed
94
        context['shares'] = shares()
95
96
        context['same_floor'] = same_floor
        context['has_flagged'] = bool(flags)
Daniel W Bond's avatar
Daniel W Bond committed
97
98
        if flags:
            context['my_flag'] = my_flag
Daniel W Bond's avatar
Daniel W Bond committed
99
100
        return context

Daniel W Bond's avatar
Daniel W Bond committed
101

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

108
109
    form_valid_message = "Your profile was successfully updated!"

110
111
112
113
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]
114
115
116
117
        try:
            student = Student.objects.get(user__username=url_uname)
        except ObjectDoesNotExist:
            raise Http404
118
119

        if not(url_uname == self.request.user.username):
120
121
            return HttpResponseRedirect(reverse('update_student',
                                                kwargs={'slug': self.request.user.username}))
122
123
124
        else:
            return super(UpdateStudent, self).get(request, *args, **kwargs)

125
126
    def get_initial(self):
        initial = super(UpdateStudent, self).get_initial()
127

128
        me = self.request.user.student
129
        majors = [pk_or_none(me, major) for major in me.major.all()]
130

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
        initial = {'first_name': me.user.first_name,
                   'last_name': me.user.last_name,
                   'gender': me.gender,
                   'show_gender': me.show_gender,
                   'room': pk_or_none(me, me.room),
                   'privacy': me.privacy,
                   'blocked_kids': me.blocked_kids.all(),
                   'major': majors,
                   'graduating_year': me.graduating_year,
                   'on_campus': me.on_campus, }

        return initial

    def get_form(self):
        form = super(UpdateStudent, self).get_form(StudentUpdateForm)

        me = self.request.user.student
148

149
        form.fields['blocked_kids'].queryset = Student.objects.exclude(user=self.request.user)
150
        form.fields['room'].widget.user = self.request.user
151

152
        if me.recent_changes() > 2:
153
            form.fields['room'].required = False
154
            form.fields['room'].widget = HiddenInput()
155
            form.fields['on_campus'].required = False
156
            form.fields['on_campus'].widget = HiddenInput()
157

158
159
        # RAs and RDs cannot move off campus
        if me.is_staff():
160
            form.fields['on_campus'].required = False
161
162
            form.fields['on_campus'].disabled = True

163
        return form
164

Daniel W Bond's avatar
Daniel W Bond committed
165
166
167
    @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
168
        # for key, value in request.POST.iteritems():
169
        #     print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
170
171
        return super(UpdateStudent, self).post(request, *args, **kwargs)

172
    def form_valid(self, form):
173
        me = self.request.user.student
174

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

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
177
        # for key, value in form.data.iteritems():
178
        #     print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
179

180
        current_room = me.room
181
182
183
184
185

        # if you somehow got around the hidden widget, you're still outta luck
        if me.recent_changes() > 2:
            form_room = current_room
        else:
186
            form_room = form.cleaned_data.get('room')
187
188

        # no room if you move off campus
189
        on_campus = form.cleaned_data.get('on_campus')
190
        if not on_campus:
191
192
            form_room = None

193
        # note this is after the 'on campus' check
194
        # remove any flags you've received
195
196
        if current_room != form_room:
            me.times_changed_room += 1
197
            Confirmation.objects.filter(student=me).delete()
198

199
        me.on_campus = on_campus
200
201
        me.room = form_room

202
203
204
205
206
        # 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:
207
            me.privacy = form.cleaned_data.get('privacy')
208

209
210
211
212
        # if you are an RA or an RD, you live on campus
        if me.is_staff():
            me.on_campus = True

213
        try:
214
215
            # in case someone disabled the js, limit processing to only the first
            # two majors passed by the user
216
            #
217
218
            # we also eliminate the potential a student manipulates the form to
            # pass in two majors of the same type by casting to a set
219
            form_majors = set(form.cleaned_data.get('major')[:2])
220
221
222
223
224
225
226
227
228
229
230
            # 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)
231
        except:
232
            # don't change majors
233
            # if someone is selecting a major pk that does not exist, don't do anything
234
            pass
235

236
        # replicate the same thing for the other m2m field
237
        try:
238
            form_blocked = set(form.cleaned_data.get('blocked_kids'))
239
240
            current_blocked = me.blocked_kids.all()
            # most people will not being blocking other students
241
            if form_blocked or current_blocked:
242
243
244
245
246
247
                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)
248
        except:
249
            pass
250

251
252
253
254
255
256
257
258
        # silently remove numbers from names
        me.user.first_name = no_nums(form.cleaned_data.get('first_name'))
        me.user.last_name = no_nums(form.cleaned_data.get('last_name'))

        me.gender = form.cleaned_data.get('gender')
        me.show_gender = form.cleaned_data.get('show_gender')
        me.graduating_year = form.cleaned_data.get('graduating_year')

259
260
261
262
263
264
        me.user.save()
        me.save()

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

    def get_success_url(self):
265
266
267

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

268
269
270
271
            msg = """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."""
            messages.add_message(self.request, messages.WARNING, msg)
272

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

276

277
class DeleteStudent(LoginRequiredMixin, StudentContextMixin, FormView):
278
279
    form_class = FarewellFeedbackForm
    template_name = 'delete_student.html'
280

281
282
283
284
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]
285
286
287
288
        try:
            student = Student.objects.get(user__username=url_uname)
        except ObjectDoesNotExist:
            raise Http404
289

290
291
292
293
294
295
296
297
298
        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):
299
300
            return HttpResponseRedirect(reverse('delete_student',
                                                kwargs={'slug': self.request.user.username}))
301
        else:
302
            return super(DeleteStudent, self).get(request, *args, **kwargs)
303

Daniel W Bond's avatar
Daniel W Bond committed
304
    def form_valid(self, form):
305
306
307
        user = self.request.user
        student = self.request.user.student

308
309
310
311
312
313
314
315
316
317
318
319
        # 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,
320
                'special_message': "We're glad you gave our service a try."
321
            }
322
        else:
323
324
325
326
            context = {
                'student_name': student.get_first_name_or_uname,
                'special_message': "We wish you luck in your time after Mason!"
            }
327

328
329
        subject = "You successfully deleted your account on Roomlist"
        to = user.email
330

331
        student_email = create_email(text_path, html_path, subject, to, context)
332

333
334
335
336
        # 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'
337

338
            date_text = student.created.strftime('%A, %B %d, %Y')
339

340
341
342
343
            if form.cleaned_data['leaving']:
                leaving = ""
            else:
                leaving = "not"
344

345
346
347
348
349
350
            context = {
                'student_name':  student.get_first_name_or_uname,
                'signup_date': date_text,
                'leaving': leaving,
                'feedback': form.cleaned_data['feedback']
            }
351

352
353
            subject = "Feedback from Roomlist account deletion"
            to = 'roomlist@lists.srct.gmu.edu'
354

355
            feedback_email = create_email(text_path, html_path, subject, to, context)
356

357
            connection.send_messages([student_email, feedback_email])
358
        else:
359
            connection.send_messages([student_email])
360

361
362
        # yes, we do have to manually close the connection
        connection.close()
363

364
365
366
367
368
        # delete both the student object and the student object
        confirmations = Confirmation.objects.filter(confirmer=student)
        if confirmations:
            for confirmation in confirmations:
                confirmation.delete()
369
370
        student.delete()
        user.delete()
371

372
        return super(DeleteStudent, self).form_valid(form)
373

374
    def get_success_url(self):
375
        return reverse('homepage')
376

Daniel W Bond's avatar
Daniel W Bond committed
377

378
# majors pages
379
class ListMajors(ListView):
Daniel W Bond's avatar
Daniel W Bond committed
380
381
382
383
384
    model = Major
    queryset = Major.objects.all().order_by('name')
    context_object_name = 'majors'
    template_name = 'list_majors.html'

385
386
387
388
389
390
391
392
393
394

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

397
398
        # 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')
399

400
        students_by_year = OrderedDict()  # we're ordering from senior on down
401

402
403
404
405
        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
406

407
        context['students_by_year'] = students_by_year
408
409

        return context
410
411
412


class CreateConfirmation(LoginRequiredMixin, CreateView):
413
414
415
    """Students on the same floor may flag one another.

    This is our attempt at crowdsourced verification."""
416
417
418
419
420
421
422
423
424
    model = Confirmation
    fields = []
    template_name = 'create_confirmation.html'

    login_url = 'login'

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

        current_url = self.request.get_full_path()
425
426
427
        # [u'', u'accounts', u'student', u'gmason', u'flag', u'confirmer']
        confirmer_uname = current_url.split('/')[3]
        student_uname = current_url.split('/')[5]
428
429
430
431
432
433
434
        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
435
436
437

        # you can't flag yourself
        if confirmer == student:
438
            raise Http404
439
440
441
442
443
444
445
446
447

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

448
449
450
        # you can't see the page if the person has banned you
        if confirmer in student.blocked_kids.all():
            raise Http404
451
452
453
454
455
456
457
458

        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()
459
        url_uname = current_url.split('/')[5]
460
461
462
463
464
465
466

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

        context['student'] = student

        return context

467
468
469
470
471
    @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)

472
473
474
475
    def form_valid(self, form):

        # duplicated code
        current_url = self.request.get_full_path()
476
        url_uname = current_url.split('/')[5]
477
478
479
480
481
482
483
484
485
486
487
488

        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
489
                       kwargs={'slug': self.object.student.slug})
490
491
492
493


class DeleteConfirmation(LoginRequiredMixin, DeleteView):
    model = Confirmation
Daniel W Bond's avatar
Daniel W Bond committed
494
    template_name = 'delete_confirmation.html'
495
496
497

    login_url = 'login'

Daniel W Bond's avatar
Daniel W Bond committed
498
    def get(self, request, *args, **kwargs):
499
500
        requester = self.request.user.student

501
502
        current_url = self.request.get_full_path()
        confirmer_uname = current_url.split('/')[3]
503
        # not catching exceptions here; that's handled in get_object
Daniel W Bond's avatar
Daniel W Bond committed
504
        confirmer = Student.objects.get(user__username=confirmer_uname)
505

506
        # only the person who created the confirmation may delete it
Daniel W Bond's avatar
Daniel W Bond committed
507
508
        if not(requester == confirmer):
            return HttpResponseForbidden()
509
        # however, if the confirmation just flat out doesn't exist...
Daniel W Bond's avatar
Daniel W Bond committed
510
        else:
511
512
513
514
515
516
            try:
                confirmer = self.get_object().confirmer
            except ObjectDoesNotExist:
                raise Http404
            else:
                return super(DeleteConfirmation, self).get(request, *args, **kwargs)
517

518
519
520
521
522
523
    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]

524
525
526
527
528
529
        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
530
        return confirmation
531
532
533

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