serve.py
16.7 KB
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
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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
339
340
341
342
343
344
345
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
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
"""
Handles the web, http & html part of the application interface.
Uses the tornadoweb framework.
"""
# python standard library
import asyncio
import base64
import functools
import json
import logging
import mimetypes
from os import path
import re
import signal
import sys
from timeit import default_timer as timer
from typing import Dict, Tuple
import uuid
# user installed libraries
import tornado
# this project
from .parser_markdown import md_to_html
# setup logger for this module
logger = logging.getLogger(__name__)
# ----------------------------------------------------------------------------
class WebApplication(tornado.web.Application):
"""
Web Application. Routes to handler classes.
"""
def __init__(self, testapp, debug=False):
handlers = [
(r"/login", LoginHandler),
(r"/logout", LogoutHandler),
(r"/review", ReviewHandler),
(r"/admin", AdminHandler),
(r"/file", FileHandler),
(r"/adminwebservice", AdminWebservice),
(r"/studentwebservice", StudentWebservice),
(r"/", RootHandler),
]
settings = {
"template_path": path.join(path.dirname(__file__), "templates"),
"static_path": path.join(path.dirname(__file__), "static"),
"static_url_prefix": "/static/",
"xsrf_cookies": True,
"cookie_secret": base64.b64encode(uuid.uuid4().bytes),
"login_url": "/login",
"debug": debug,
}
super().__init__(handlers, **settings)
self.testapp = testapp
# ----------------------------------------------------------------------------
def admin_only(func):
"""
Decorator to restrict access to the administrator:
@admin_only
def get(self):
"""
@functools.wraps(func)
async def wrapper(self, *args, **kwargs):
if self.current_user != "0":
raise tornado.web.HTTPError(403) # forbidden
await func(self, *args, **kwargs)
return wrapper
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
class BaseHandler(tornado.web.RequestHandler):
"""
Handlers should inherit this one instead of tornado.web.RequestHandler.
It automatically gets the user cookie, which is required to identify the
user in most handlers.
"""
@property
def testapp(self):
"""simplifies access to the application a little bit"""
return self.application.testapp
# @property
# def debug(self) -> bool:
# '''check if is running in debug mode'''
# return self.application.testapp.debug
def get_current_user(self):
"""
Since HTTP is stateless, a cookie is used to identify the user.
This function returns the cookie for the current user.
"""
cookie = self.get_secure_cookie("perguntations_user")
if cookie:
return cookie.decode("utf-8")
return None
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
class LoginHandler(BaseHandler):
"""Handles /login"""
_prefix = re.compile(r"[a-z]")
_error_msg = {
"wrong_password": "Senha errada",
"not_allowed": "Não está autorizado a fazer o teste",
"nonexistent": "Número de aluno inválido",
}
def get(self):
"""Render login page."""
self.render("login.html", error="")
async def post(self):
"""Authenticates student and login."""
uid = self.get_body_argument("uid")
password = self.get_body_argument("pw")
headers = {
"remote_ip": self.request.remote_ip,
"user_agent": self.request.headers.get("User-Agent"),
}
error = await self.testapp.login(uid, password, headers)
if error is not None:
await asyncio.sleep(3) # delay to avoid spamming the server...
self.render("login.html", error=self._error_msg[error])
else:
self.set_secure_cookie("perguntations_user", str(uid))
self.redirect("/")
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
class LogoutHandler(BaseHandler):
"""Handle /logout"""
@tornado.web.authenticated
def get(self):
"""Logs out a user."""
self.testapp.logout(self.current_user)
self.clear_cookie("perguntations_user")
self.render("login.html", error="")
# ----------------------------------------------------------------------------
# Handles the TEST
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
class RootHandler(BaseHandler):
"""
Presents test to student.
Receives answers, corrects the test and sends back the grade.
Redirects user 0 to /admin.
"""
_templates = {
# -- question templates --
"radio": "question-radio.html",
"checkbox": "question-checkbox.html",
"text": "question-text.html",
"text-regex": "question-text.html",
"numeric-interval": "question-text.html",
"textarea": "question-textarea.html",
# -- information panels --
"information": "question-information.html",
"success": "question-information.html",
"warning": "question-information.html",
"alert": "question-information.html",
}
# --- GET
@tornado.web.authenticated
async def get(self):
"""
Handles GET /
Sends test to student or redirects 0 to admin page.
Multiple calls to this function will return the same test.
"""
uid = self.current_user
logger.debug('"%s" GET /', uid)
if uid == "0":
self.redirect("/admin")
else:
test = self.testapp.get_test(uid)
name = self.testapp.get_name(uid)
self.render(
"test.html",
t=test,
uid=uid,
name=name,
md=md_to_html,
templ=self._templates,
debug=self.testapp.debug,
)
# --- POST
@tornado.web.authenticated
async def post(self):
"""
Receives answers, fixes some html weirdness, corrects test and
renders the grade.
self.request.arguments = {'answered-0': [b'on'], '0': [b'13.45']}
builds dictionary ans = {0: 'answer0', 1:, 'answer1', ...}
unanswered questions are not included.
"""
starttime = timer() # performance timer
uid = self.current_user
logger.debug('"%s" POST /', uid)
test = self.testapp.get_test(uid)
if test is None:
logger.warning('"%s" submitted but no test running - Err 403', uid)
raise tornado.web.HTTPError(403) # Forbidden
ans = {}
for i, question in enumerate(test["questions"]):
qid = str(i)
if f"answered-{qid}" in self.request.arguments:
ans[i] = self.get_body_arguments(qid)
# remove enclosing list in some question types
if question["type"] == "radio":
ans[i] = ans[i][0] if ans[i] else None
elif question["type"] in (
"text",
"text-regex",
"textarea",
"numeric-interval",
):
ans[i] = ans[i][0]
# submit answered questions, correct
await self.testapp.submit_test(uid, ans)
name = self.testapp.get_name(uid)
self.render("grade.html", t=test, uid=uid, name=name)
self.clear_cookie("perguntations_user")
self.testapp.logout(uid)
logger.info(" elapsed time: %fs", timer() - starttime)
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
# FIXME: also to update answers
class StudentWebservice(BaseHandler):
"""
Receive ajax from students during the test in response to the events
focus, unfocus and resize, etc.
"""
@tornado.web.authenticated
def post(self):
"""handle ajax post"""
uid = self.current_user
cmd = self.get_body_argument("cmd", None)
value = self.get_body_argument("value", None)
if cmd is not None and value is not None:
self.testapp.register_event(uid, cmd, json.loads(value))
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
class AdminWebservice(BaseHandler):
"""
Receive ajax requests from admin
"""
@tornado.web.authenticated
@admin_only
async def get(self):
"""admin webservices that do not change state"""
cmd = self.get_query_argument("cmd")
logger.debug("GET /adminwebservice %s", cmd)
if cmd == "testcsv":
test_ref, data = self.testapp.get_grades_csv()
self.set_header("Content-Type", "text/csv")
self.set_header(
"content-Disposition", f"attachment; filename={test_ref}.csv"
)
self.write(data)
await self.flush()
elif cmd == "questionscsv":
test_ref, data = self.testapp.get_detailed_grades_csv()
self.set_header("Content-Type", "text/csv")
self.set_header(
"content-Disposition", f"attachment; filename={test_ref}-detailed.csv"
)
self.write(data)
await self.flush()
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
class AdminHandler(BaseHandler):
"""Handle /admin"""
# --- GET
@tornado.web.authenticated
@admin_only
async def get(self):
"""
Admin page.
"""
cmd = self.get_query_argument("cmd", default=None)
logger.debug("GET /admin (cmd=%s)", cmd)
if cmd is None:
self.render("admin.html")
elif cmd == "test":
data = {"data": self.testapp.get_test_config()}
self.write(json.dumps(data, default=str))
elif cmd == "students_table":
data = {"data": self.testapp.get_students_state()}
self.write(json.dumps(data, default=str))
# --- POST
@tornado.web.authenticated
@admin_only
async def post(self):
"""
Executes commands from the admin page.
"""
cmd = self.get_body_argument("cmd", None)
value = self.get_body_argument("value", None)
logger.debug("POST /admin (cmd=%s, value=%s)", cmd, value)
if cmd == "allow":
self.testapp.allow_student(value)
elif cmd == "deny":
self.testapp.deny_student(value)
elif cmd == "allow_all":
self.testapp.allow_all_students()
elif cmd == "deny_all":
self.testapp.deny_all_students()
elif cmd == "reset_password":
await self.testapp.set_password(uid=value, password="")
elif cmd == "insert_student" and value is not None:
student = json.loads(value)
await self.testapp.insert_new_student(
uid=student["number"], name=student["name"]
)
# ----------------------------------------------------------------------------
# Serves files from the /public subdir of the topics.
# ----------------------------------------------------------------------------
# pylint: disable=abstract-method
class FileHandler(BaseHandler):
"""
Handles static files from questions like images, etc.
"""
_filecache: Dict[Tuple[str, str], bytes] = {}
@tornado.web.authenticated
async def get(self):
"""
Returns requested file. Files are obtained from the 'public' directory
of each question.
"""
uid = self.current_user
ref = self.get_query_argument("ref", None)
image = self.get_query_argument("image", None)
logger.debug("GET /file (ref=%s, image=%s)", ref, image)
if ref is None or image is None:
return
content_type = mimetypes.guess_type(image)[0]
if (ref, image) in self._filecache:
logger.debug("using cached file")
self.write(self._filecache[(ref, image)])
if content_type is not None:
self.set_header("Content-Type", content_type)
await self.flush()
return
try:
test = self.testapp.get_test(uid)
except KeyError:
logger.warning("Could not get test to serve image file")
raise tornado.web.HTTPError(404) from None # Not Found
# search for the question that contains the image
for question in test["questions"]:
if question["ref"] == ref:
filepath = path.join(question["path"], "public", image)
try:
with open(filepath, "rb") as file:
data = file.read()
except OSError:
logger.error('Error reading file "%s"', filepath)
return
self._filecache[(ref, image)] = data
self.write(data)
if content_type is not None:
self.set_header("Content-Type", content_type)
await self.flush()
return
# --- REVIEW -----------------------------------------------------------------
# pylint: disable=abstract-method
class ReviewHandler(BaseHandler):
"""
Show test for review
"""
_templates = {
"radio": "review-question-radio.html",
"checkbox": "review-question-checkbox.html",
"text": "review-question-text.html",
"text-regex": "review-question-text.html",
"numeric-interval": "review-question-text.html",
"textarea": "review-question-text.html",
# -- information panels --
"information": "review-question-information.html",
"success": "review-question-information.html",
"warning": "review-question-information.html",
"alert": "review-question-information.html",
}
@tornado.web.authenticated
@admin_only
async def get(self):
"""
Opens JSON file with a given corrected test and renders it
"""
test_id = self.get_query_argument("test_id", None)
logger.info("Review test %s.", test_id)
fname = self.testapp.get_json_filename_of_test(test_id)
if fname is None:
raise tornado.web.HTTPError(404) # Not Found
try:
with open(path.expanduser(fname), encoding="utf-8") as jsonfile:
test = json.load(jsonfile)
except OSError:
msg = f'Cannot open "{fname}" for review.'
logger.error(msg)
raise tornado.web.HTTPError(status_code=404, reason=msg) from None
except json.JSONDecodeError as exc:
msg = f'JSON error in "{fname}": {exc}'
logger.error(msg)
raise tornado.web.HTTPError(status_code=404, reason=msg)
uid = test["student"]
name = self.testapp.get_name(uid)
self.render(
"review.html",
t=test,
uid=uid,
name=name,
md=md_to_html,
templ=self._templates,
debug=self.testapp.debug,
)
# ----------------------------------------------------------------------------
def signal_handler(*_):
"""
Catches Ctrl-C and stops webserver
"""
reply = input(" --> Stop webserver? (yes/no) ")
if reply.lower() == "yes":
tornado.ioloop.IOLoop.current().stop()
logger.critical("Webserver stopped.")
sys.exit(0)
# ----------------------------------------------------------------------------
def run_webserver(app, ssl_opt, port, debug):
"""
Starts and runs webserver until a SIGINT signal (Ctrl-C) is received.
"""
# --- create web application
logger.info("-------- Starting WebApplication (tornado) --------")
try:
webapp = WebApplication(app, debug=debug)
except Exception:
logger.critical("Failed to start web application.")
raise
# --- create httpserver
try:
httpserver = tornado.httpserver.HTTPServer(webapp, ssl_options=ssl_opt)
except ValueError:
logger.critical("Certificates cert.pem, privkey.pem not found")
sys.exit(1)
try:
httpserver.listen(port)
except OSError:
logger.critical("Cannot bind port %d. Already in use?", port)
sys.exit(1)
logger.info("Listening on port %d... (Ctrl-C to stop)", port)
signal.signal(signal.SIGINT, signal_handler)
# --- run webserver
try:
tornado.ioloop.IOLoop.current().start() # running...
except Exception:
logger.critical("Webserver stopped!")
tornado.ioloop.IOLoop.current().stop()
raise