Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- coding: utf-8 -*-
from __future__ import division
__copyright__ = "Copyright (C) 2015 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from django.contrib.auth import get_user_model
import django.forms as forms
from django.utils.translation import ugettext, ugettext_lazy as _
from django.shortcuts import ( # noqa
render, get_object_or_404, redirect)
from django.core.exceptions import ( # noqa
PermissionDenied, ObjectDoesNotExist, SuspiciousOperation)
from django.contrib import messages # noqa
from django.contrib.auth.decorators import permission_required
from django.db import transaction
from crispy_forms.layout import Submit
from course.models import Exam, ExamTicket, Participation, FlowSession
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from course.utils import course_view, render_course_page
from course.constants import (
exam_ticket_states,
participation_status,
participation_role)
from course.views import get_now_or_fake_time
from relate.utils import StyledForm
ticket_alphabet = "ABCDEFGHJKLPQRSTUVWXYZabcdefghjkpqrstuvwxyz23456789"
def gen_ticket_code():
from random import choice
return "".join(choice(ticket_alphabet) for i in range(8))
# {{{ issue ticket
class UserChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
user = obj
return (
_("%(user_email)s - %(user_lastname)s, "
"%(user_firstname)s")
% {
"user_email": user.email,
"user_lastname": user.last_name,
"user_firstname": user.first_name})
class IssueTicketForm(StyledForm):
def __init__(self, *args, **kwargs):
initial_exam = kwargs.pop("initial_exam", None)
super(IssueTicketForm, self).__init__(*args, **kwargs)
self.fields["user"] = UserChoiceField(
queryset=(get_user_model().objects
.filter(
is_active=True,
)
.order_by("last_name")),
required=True,
help_text=_("Select participant for whom exception is to "
"be granted."),
label=_("Participant"))
self.fields["exam"] = forms.ModelChoiceField(
queryset=(
Exam.objects.filter(
active=True)),
required=True,
initial=initial_exam,
label=_("Exam"))
self.fields["revoke_prior"] = forms.BooleanField(
label=_("Revoke prior exam tickets for this user"),
required=False,
initial=True)
self.helper.add_input(
Submit(
"issue",
_("Issue ticket"),
css_class="col-lg-offset-2"))
@permission_required("course.can_issue_exam_tickets")
def issue_exam_ticket(request):
if request.method == "POST":
form = IssueTicketForm(request.POST)
if form.is_valid():
exam = form.cleaned_data["exam"]
try:
participation = Participation.objects.get(
course=exam.course,
user=form.cleaned_data["user"],
status=participation_status.active,
)
except ObjectDoesNotExist:
messages.add_message(request, messages.ERROR,
_("User is not enrolled in course."))
participation = None
if participation is not None:
if form.cleaned_data["revoke_prior"]:
ExamTicket.objects.filter(
exam=exam,
participation=participation,
state=exam_ticket_states.valid,
).update(state=exam_ticket_states.revoked)
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
ticket = ExamTicket()
ticket.exam = exam
ticket.participation = participation
ticket.creator = request.user
ticket.state = exam_ticket_states.valid
ticket.code = gen_ticket_code()
ticket.save()
messages.add_message(request, messages.SUCCESS,
_(
"Ticket issued for <b>%s</b>. "
"The ticket code is <b>%s</b>."
) % (participation, ticket.code))
form = IssueTicketForm(initial_exam=exam)
else:
form = IssueTicketForm()
return render(request, "generic-form.html", {
"form_description":
_("Issue Exam Ticket"),
"form": form,
})
# }}}
# {{{ batch-issue tickets
class BatchIssueTicketsForm(StyledForm):
def __init__(self, course, *args, **kwargs):
super(BatchIssueTicketsForm, self).__init__(*args, **kwargs)
self.fields["exam"] = forms.ModelChoiceField(
queryset=(
Exam.objects.filter(
course=course,
active=True
)),
required=True,
label=_("Exam"))
self.fields["format"] = forms.ChoiceField(
choices=(
("list", _("List")),
("cards", _("Cards")),
),
label=_("Ticket Format"),
required=True)
self.fields["revoke_prior"] = forms.BooleanField(
label=_("Revoke prior exam tickets"),
required=False,
initial=False)
self.helper.add_input(
Submit(
"issue",
_("Issue tickets"),
css_class="col-lg-offset-2"))
@course_view
@transaction.atomic
def batch_issue_exam_tickets(pctx):
if pctx.role not in [
participation_role.instructor,
]:
raise PermissionDenied(
_("must be instructor or TA to batch-issue tickets"))
form_text = ""
request = pctx.request
if request.method == "POST":
form = BatchIssueTicketsForm(pctx.course, request.POST)
if form.is_valid():
exam = form.cleaned_data["exam"]
if form.cleaned_data["revoke_prior"]:
ExamTicket.objects.filter(
exam=exam,
state=exam_ticket_states.valid,
).update(state=exam_ticket_states.revoked)
tickets = []
for participation in (
Participation.objects.filter(
course=pctx.course,
status=participation_status.active)
.order_by(
"user__username")):
ticket = ExamTicket()
ticket.exam = exam
ticket.participation = participation
ticket.creator = request.user
ticket.state = exam_ticket_states.valid
ticket.code = gen_ticket_code()
ticket.save()
tickets.append(ticket)
from django.template.loader import render_to_string
form_text = render_to_string(
"course/exam-ticket-%s.html" % form.cleaned_data["format"],
{"tickets": tickets})
messages.add_message(request, messages.SUCCESS,
_("%d tickets issued.") % len(tickets))
form = None
else:
form = BatchIssueTicketsForm(pctx.course)
return render_course_page(pctx, "course/generic-course-form.html", {
"form": form,
"form_text": form_text,
"form_description": ugettext("Batch-Issue Exam Tickets")
})
# }}}
# {{{ check in
class ExamTicketBackend(object):
def authenticate(self, username=None, code=None, now_datetime=None):
try:
user = get_user_model().objects.get(
username=username,
is_active=True)
ticket = ExamTicket.objects.get(
participation__user=user,
code=code,
state=exam_ticket_states.valid,
)
if ticket.exam.no_exams_before >= now_datetime:
return None
if (
ticket.exam.no_exams_after is not None
and
ticket.exam.no_exams_after <= now_datetime):
return None
except ObjectDoesNotExist:
return None
return user
def get_user(self, user_id):
try:
return get_user_model().objects.get(pk=user_id)
except get_user_model().DoesNotExist:
return None
class ExamCheckInForm(StyledForm):
username = forms.CharField(required=True, label=_("User name"),
# For now, until we upgrade to a custom user model.
max_length=30,
help_text=_("This is typically your full email address."))
code = forms.CharField(required=True, label=_("Code"),
widget=forms.PasswordInput())
def __init__(self, *args, **kwargs):
super(ExamCheckInForm, self).__init__(*args, **kwargs)
self.helper.add_input(
Submit("submit", _("Check in"),
css_class="col-lg-offset-2"))
def check_in_for_exam(request):
now_datetime = get_now_or_fake_time(request)
if request.method == "POST":
form = ExamCheckInForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
code = form.cleaned_data["code"]
from django.contrib.auth import authenticate, login
user = authenticate(username=username, code=code,
now_datetime=now_datetime)
if user is None:
messages.add_message(request, messages.ERROR,
_("Invalid check-in data."))
else:
login(request, user)
ticket = ExamTicket.objects.get(
participation__user=user,
code=code,
state=exam_ticket_states.valid,
)
ticket.state = exam_ticket_states.used
ticket.usage_time = now_datetime
ticket.save()
request.session["relate_session_exam_ticket_pk"] = ticket.pk
return redirect("relate-view_start_flow",
ticket.exam.course.identifier,
ticket.exam.flow_id)
else:
form = ExamCheckInForm()
return render(request, "generic-form.html", {
"form_description":
_("Check in for Exam"),
"form": form
})
# }}}
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# {{{ lockdown middleware
class ExamLockdownMiddleware(object):
def process_request(self, request):
request.relate_exam_lockdown = False
if "relate_session_exam_ticket_pk" in request.session:
ticket_pk = request.session['relate_session_exam_ticket_pk']
try:
ticket = ExamTicket.objects.get(pk=ticket_pk)
except ObjectDoesNotExist:
messages.add_message(request, messages.ERROR,
_("Error while processing exam lockdown: ticket not found."))
if not ticket.exam.lock_down_sessions:
return None
request.relate_exam_lockdown = True
flow_session_ids = [fs.id for fs in FlowSession.objects.filter(
participation=ticket.participation,
flow_id=ticket.exam.flow_id)]
from django.core.urlresolvers import resolve
resolver_match = resolve(request.path)
from course.views import (get_repo_file, get_current_repo_file)
from course.flow import (view_start_flow, view_flow_page,
update_expiration_mode, finish_flow_session_view)
from course.auth import user_profile
from django.contrib.auth.views import logout
ok = False
if resolver_match.func in [
get_repo_file,
get_current_repo_file,
user_profile,
logout]:
ok = True
if (resolver_match.func == view_start_flow
and
resolver_match.kwargs["course_identifier"]
== ticket.exam.course.identifier
and
resolver_match.kwargs["flow_id"]
== ticket.exam.flow_id):
ok = True
if (
resolver_match.func in [
view_flow_page,
update_expiration_mode,
finish_flow_session_view]
and
int(resolver_match.kwargs["flow_session_id"])
in flow_session_ids):
ok = True
if not ok:
raise PermissionDenied("not allowed in exam lock-down")
# }}}
# {{{ lockdown context processor
def exam_lockdown_context_processor(request):
return {
"relate_exam_lockdown": request.relate_exam_lockdown,
}
# }}}