views.py 16.2 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 operator import attrgetter
from itertools import chain
7
# core django imports
8
from django.http import HttpResponseForbidden, HttpResponseRedirect, Http404
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
9
from django.views.generic import CreateView, ListView, DetailView, 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
from .models import Student, Major, Confirmation
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
20
from housing.models import Room
21
from .forms import StudentUpdateForm
22
from .student_messages import return_messages
23

24
25

def custom_cas_login(request, *args, **kwargs):
26
    """If a student has not completed the welcome walkthrough, go there on login."""
27
28
    response = cas_login(request, *args, **kwargs)
    # returns HttpResponseRedirect
29

30
31
    if request.user.is_authenticated():

32
33
34
        if not request.user.student.totally_done():

            if not request.user.student.completedName:
35
                return HttpResponseRedirect(reverse('welcomeName'))
36
            elif not request.user.student.completedPrivacy:
37
                return HttpResponseRedirect(reverse('welcomePrivacy'))
38
            elif not request.user.student.completedMajor:
39
                return HttpResponseRedirect(reverse('welcomeMajor'))
40
            elif not request.user.completedSocial:
41
                return HttpResponseRedirect(reverse('welcomeSocial'))
42
43
44
        else:
            welcome_back = random.choice(return_messages)
            messages.add_message(request, messages.INFO, mark_safe(welcome_back))
45
46
47
48

    return response


49
# only two students on the same floor can confirm one another (crowdsourced verification)
50
51
def on_the_same_floor(student, confirmer):
    if student == confirmer:
52
        # Student is confirmer
53
54
55
56
57
        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):
58
        # one Student is None
59
60
        return False
    elif not(student_floor == confirmer_floor):
61
        # not the same floor
62
63
64
65
66
        return False
    else:
        return True


67
68
69
70
71
72
def pk_or_none(me, obj):
    if obj is None:
        return None
    else:
        return obj.pk

73

74
75
76
# details about the student
class DetailStudent(LoginRequiredMixin, DetailView):
    model = Student
77
78
79
80
    context_object_name = 'student'
    template_name = 'detailStudent.html'

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

82
83
84
85
    def get(self, request, *args, **kwargs):

        current_url = self.request.get_full_path()
        url_uname = current_url.split('/')[3]
86
        detailed_student = Student.objects.get(user__username=url_uname)
87
88
89
90
91
92

        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
93
94
95
    def get_context_data(self, **kwargs):
        context = super(DetailStudent, self).get_context_data(**kwargs)

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

98
99
100
101
102
        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
103
104
105
106
107
        if flags:
            try:
                my_flag = Confirmation.objects.get(confirmer=requesting_student,
                                                   student=self.get_object())
            except Exception as e:
108
109
                print("Students are not supposed to be able to make more than one flag per student.")
                print(e)
110

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
111
        # recognizably too complex
Daniel W Bond's avatar
Daniel W Bond committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
        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
129
130
            # 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
131
132
133
134
135
136
            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
137

Daniel W Bond's avatar
Daniel W Bond committed
138
        context['shares'] = shares()
139
140
        context['same_floor'] = same_floor
        context['has_flagged'] = bool(flags)
Daniel W Bond's avatar
Daniel W Bond committed
141
142
        if flags:
            context['my_flag'] = my_flag
Daniel W Bond's avatar
Daniel W Bond committed
143
144
        return context

Daniel W Bond's avatar
Daniel W Bond committed
145

146
# update a student, but FormView to allow name update on same page
147
class UpdateStudent(LoginRequiredMixin, FormValidMessageMixin, FormView):
148
    template_name = 'update_student.html'
149
    form_class = StudentUpdateForm
150
151
    login_url = 'login'

152
153
    form_valid_message = "Your profile was successfully updated!"

154
155
156
157
158
159
160
161
162
163
    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)

164
165
166
167
    def get_context_data(self, **kwargs):
        context = super(UpdateStudent, self).get_context_data(**kwargs)

        me = Student.objects.get(user=self.request.user)
168
        majors = [pk_or_none(me, major) for major in me.major.all()]
169
170

        form = StudentUpdateForm(initial={'first_name': me.user.first_name,
171
172
                                          'last_name': me.user.last_name,
                                          'gender': me.gender,
173
                                          'show_gender': me.show_gender,
174
175
                                          'room': pk_or_none(me, me.room),
                                          'privacy': me.privacy,
176
                                          'blocked_kids': me.blocked_kids.all(),
177
                                          'major': majors,
178
179
                                          'graduating_year': me.graduating_year,
                                          'on_campus': me.on_campus, })
180

181
        if me.recent_changes() > 2:
182
            form.fields['room'].widget = HiddenInput()
183
184
            form.fields['privacy'].widget = HiddenInput()
            form.fields['on_campus'].widget = HiddenInput()
185
186
        else:
            form.fields['room'].widget.user = self.request.user
187

188
189
190
191
192
        # 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'

193
194
195
        # chosen
        form.fields['major'].widget.attrs['class'] = 'chosen-select'

196
        context['my_form'] = form
Daniel W Bond's avatar
Daniel W Bond committed
197

198
199
        return context

Daniel W Bond's avatar
Daniel W Bond committed
200
201
202
    @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
203
        # for key, value in request.POST.iteritems():
204
        #     print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
205
206
        return super(UpdateStudent, self).post(request, *args, **kwargs)

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

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

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
212
        # for key, value in form.data.iteritems():
213
        #     print(key, value)
Daniel W Bond's avatar
Daniel W Bond committed
214

215
        current_room = me.room
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230

        # 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:
231
232
            form_room = None

233
        # note this is after the 'on campus' check
234
235
        if current_room != form_room:
            me.times_changed_room += 1
236
            Confirmation.objects.filter(student=me).delete()
237

238
        me.on_campus = on_campus
239
240
241
        me.room = form_room

        try:
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
            # 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)
260
        except:
261
262
            # don't change majors
            pass
263

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

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

    def get_success_url(self):
277
278
279
280
281

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

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

285

286
# majors pages
287
class ListMajors(ListView):
Daniel W Bond's avatar
Daniel W Bond committed
288
289
290
291
292
    model = Major
    queryset = Major.objects.all().order_by('name')
    context_object_name = 'majors'
    template_name = 'list_majors.html'

293
294
295
296
297
298
299
300
301
302

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)
303
        requesting_student = Student.objects.get(user=self.request.user)
304

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
305
306
307
308
309
310
311
        # retrieve every room that has a student with the major in question
        neighbourhoods = ("aq", "ra", "sh")
        visible_by_neighbourhood = {}
        for neighbourhood in neighbourhoods:
            rooms = [
                room
                for room in Room.objects.filter(floor__building__neighbourhood=neighbourhood)
312
                if room.student_set.filter(major__in=[self.get_object()])
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
313
314
315
316
317
318
319
320
321
322
323
324
325
            ]

            # identify if the student(s) in that room are visible to the requesting student
            # 'chain' is necessary if there are multiple students in one room with the same major
            #
            # we sort each of the lists of students by their username
            # as elsewhere, this is imperfect if a student changes their display name
            # this is necessary as a separate step because .visible returns a list type
            # note we're using '.' instead of '__', because who likes syntactical consistency
            visible_by_neighbourhood[neighbourhood] = sorted(list(chain(*[
                Student.objects.visible(requesting_student, room)
                for room in rooms
            ])), key=attrgetter('user.username'))
326

327
        # see what students are left over (aren't visible)
328
        hidden = set(Student.objects.filter(major__in=[self.get_object()]).order_by('user__username'))
329
        # print(hidden)
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
330
        for visible in visible_by_neighbourhood.values():
331
            # print('visible', visible)
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
332
            hidden = hidden.difference(set(visible))
333
334
            # print(hidden)

Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
335
336
337
        for neighbourhood, visible in visible_by_neighbourhood.iteritems():
            context['%s_location_visible' % neighbourhood] = visible
            context['location_hidden'] = hidden
338
339

        return context
340
341
342


class CreateConfirmation(LoginRequiredMixin, CreateView):
343
344
345
    """Students on the same floor may flag one another.

    This is our attempt at crowdsourced verification."""
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    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()

376
377
378
379
        # you can't see the page if the person has banned you
        if confirmer in student.blocked_kids.all():
            raise Http404

380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
        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

395
396
397
398
399
    @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)

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    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',
Daniel W Bond's avatar
pep8 me    
Daniel W Bond committed
417
                       kwargs={'slug': self.object.student.slug})
418
419
420
421


class DeleteConfirmation(LoginRequiredMixin, DeleteView):
    model = Confirmation
Daniel W Bond's avatar
Daniel W Bond committed
422
    template_name = 'delete_confirmation.html'
423
424
425

    login_url = 'login'

Daniel W Bond's avatar
Daniel W Bond committed
426
427
428
    def get(self, request, *args, **kwargs):
        requester = Student.objects.get(user=self.request.user)
        confirmer = self.get_object().confirmer
429

Daniel W Bond's avatar
Daniel W Bond committed
430
431
432
433
        if not(requester == confirmer):
            return HttpResponseForbidden()
        else:
            return super(DeleteConfirmation, self).get(request, *args, **kwargs)
434
435
436

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