serve.py 15.3 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
#!/usr/bin/env python3

from os import path
import sys
import argparse
import logging.config
import json

try:
    # required here
    import cherrypy
    from mako.lookup import TemplateLookup
    # required elsewhere
    from json import __version__ as json_version
    from bcrypt import __version__ as bcrypt_version
    from sqlalchemy import __version__ as alchemy_version
    from yaml import __version__ as yaml_version
    from markdown import version as markdown_version
except ImportError:
    print('''
        Some python packages are missing.
        Try running "pip3 install --user cherrypy mako markdown pyyaml pygments sqlalchemy bcrypt"
        See README.md for instructions.
        ''')
    sys.exit(1)

from tools import load_yaml

# ============================================================================
#   Authentication
#   http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions
# ============================================================================
def check_auth(*args, **kwargs):
    """A tool that looks in config for 'auth.require'. If found and it
    is not None, a login is required and the entry is evaluated as a list of
    conditions that the user must fulfill"""
    conditions = cherrypy.request.config.get('auth.require', None)
    if conditions is not None:
        username = cherrypy.session.get(SESSION_KEY)
        if username:
            # user logged in
            cherrypy.request.login = username
            for condition in conditions:
                # A condition is just a callable that returns true or false
                if not condition():
                    raise cherrypy.HTTPRedirect("/")
        else:
            # user not currently logged in
            raise cherrypy.HTTPRedirect("/login")
cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth)


# A decorator that appends conditions to the auth.require config variable.
def require(*conditions):
    def decorate(f):
        if not hasattr(f, '_cp_config'):
            f._cp_config = dict()
        f._cp_config.setdefault('auth.require', []).extend(conditions)
        return f
    return decorate


def name_is(reqd_username):
    return lambda: reqd_username == cherrypy.request.login


# ============================================================================
#   Improve cherrypy security
#   http://docs.cherrypy.org/en/latest/advanced.html#securing-your-server
# ============================================================================
def secureheaders():
    headers = cherrypy.response.headers
    headers['X-Frame-Options'] = 'DENY'
    headers['X-XSS-Protection'] = '1; mode=block'
    # FIXME disabled because MathJax requires unsafe javascript eval:
    # headers['Content-Security-Policy'] = "default-src 'self'"
    if (cherrypy.server.ssl_certificate != None and cherrypy.server.ssl_private_key != None):
         headers['Strict-Transport-Security'] = 'max-age=31536000'  # one year


# ============================================================================
#   Admin webservice
# ============================================================================
class AdminWebService(object):
    exposed = True
    _cp_config = {
        'auth.require': [name_is('0')]
    }

    def __init__(self, app):
        self.app = app

    @cherrypy.tools.accept(media='application/json') # FIXME
    def GET(self):
        data = {
            'students': self.app.get_students_state(),
            'test': self.app.testfactory
        }
        return json.dumps(data, default=str)

    @cherrypy.tools.accept(media='application/json') # FIXME
    def POST(self, **args):
        if args['cmd'] == 'allow':
            if args['value'] == 'true':
                return self.app.allow_student(args['name'])
            else:
                return self.app.deny_student(args['name'])

        elif args['cmd'] == 'reset':
            return self.app.reset_password(args['name'])

        elif args['cmd'] == 'insert':
            return self.app.insert_new_student(uid=args['number'], name=args['name'])

        else:
            print(args) # FIXME

# ============================================================================
#   Student webservice
# ============================================================================
class StudentWebService(object):
    exposed = True
    _cp_config = {
        'auth.require': []
    }

    def __init__(self, app):
        self.app = app

    @cherrypy.tools.accept(media='application/json') # FIXME
    def POST(self, **args):
        # uid = cherrypy.session.get(SESSION_KEY)
        if args['cmd'] == 'focus':
            v = json.loads(args['value'])
            self.app.set_student_focus(uid=args['number'], value=v)

# ============================================================================
#   Webserver root
# ============================================================================
class Root(object):
    def __init__(self, app):
        self.app = app
        t = TemplateLookup(directories=[TEMPLATES_DIR], input_encoding='utf-8')
        self.template = {
            'login':  t.get_template('/login.html'),
            'test':   t.get_template('/test.html'),
            'grade':  t.get_template('/grade.html'),
            'admin':  t.get_template('/admin.html'),
            'review': t.get_template('/review.html'),
        }

    # --- DEFAULT ------------------------------------------------------------
    @cherrypy.expose
    @require()
    def default(self, *args, **kwargs):
        uid = cherrypy.session.get(SESSION_KEY)
        if uid == '0':
            raise cherrypy.HTTPRedirect('/admin')
        else:
            raise cherrypy.HTTPRedirect('/test')

    # --- LOGIN --------------------------------------------------------------
    @cherrypy.expose
    def login(self, uid=None, pw=None):
        if uid is None or pw is None:   # first try
            return self.template['login'].render()

        if self.app.login(uid, pw):     # ok
            cherrypy.session[SESSION_KEY] = cherrypy.request.login = uid
            self.app.set_user_agent(uid, cherrypy.request.headers.get('User-Agent', ''))
            self.app.set_user_ip(uid, cherrypy.request.remote.ip)
            raise cherrypy.HTTPRedirect('/')
        else:                           # denied
            return self.template['login'].render()

    # --- LOGOUT -------------------------------------------------------------
    @cherrypy.expose
    @require()
    def logout(self):
        uid = cherrypy.session.get(SESSION_KEY)
        cherrypy.lib.sessions.expire()  # session coockie expires client side
        cherrypy.session[SESSION_KEY] = cherrypy.request.login = None
        cherrypy.log.error('Student {0} logged out.'.format(uid), 'APPLICATION')
        self.app.logout(uid)
        raise cherrypy.HTTPRedirect('/')

    # --- TEST ---------------------------------------------------------------
    # Get student number and assigned questions from current session.
    # If it's the first time, create instance of the test and register the
    # time.
    @cherrypy.expose
    @require()
    def test(self):
        uid = cherrypy.session.get(SESSION_KEY)
        test = self.app.get_test(uid) or self.app.generate_test(uid)
        return self.template['test'].render(t=test)

    # --- CORRECT ------------------------------------------------------------
    @cherrypy.expose
    @require()
    def correct(self, **kwargs):
        # receives dictionary with answers
        # kwargs = {'answered-0': 'on', '0': '13.45', ...}
        # Format:
        #   checkbox - all off -> no key, 1 on -> string '0', >1 on -> ['0', '1']
        #   radio    - all off -> no key, 1 on -> string '0'
        #   text     - always returns string. no answer '', otherwise 'dskdjs'
        uid = cherrypy.session.get(SESSION_KEY)
        t = self.app.get_test(uid)

        # build dictionary ans={0: 'answer0', 1:, 'answer1', ...}
        # questions not answer are not included.
        ans = {}
        for i, q in enumerate(t['questions']):
            if 'answered-' + str(i) in kwargs:
                ans[i] = kwargs.get(str(i), None)

                # Begin HACK
                #   checkboxes in html do not have a stable type:
                #   returns None instead of [], when no checkboxes are selected
                #   returns '5' instead of ['5'], when one checkbox is selected
                #   returns correctly ['1', '3'], on multiple selections
                #   we fix it to always return a list
                if q['type'] == 'checkbox':
                    if ans[i] is None:
                        ans[i] = []
                    elif isinstance(ans[i], str):
                        ans[i] = [ans[i]]
                # end HACK

        self.app.correct_test(uid, ans)
        self.app.logout(uid)

        # --- Expire session
        cherrypy.lib.sessions.expire()  # session coockie expires client side
        cherrypy.session[SESSION_KEY] = cherrypy.request.login = None

        # --- Show result to student
        return self.template['grade'].render(
            t=t,
            allgrades=self.app.get_student_grades_from_all_tests(uid)
            )

    # --- GIVEUP -------------------------------------------------------------
    @cherrypy.expose
    @require()
    def giveup(self):
        uid = cherrypy.session.get(SESSION_KEY)

        t = self.app.giveup_test(uid)
        self.app.logout(uid)

        # --- Expire session
        cherrypy.lib.sessions.expire()  # session coockie expires client side
        cherrypy.session[SESSION_KEY] = cherrypy.request.login = None

        # --- Show result to student
        return self.template['grade'].render(
            t=t,
            allgrades=self.app.get_student_grades_from_all_tests(uid)
            )

    # --- FILE ---------------------------------------------------------------
    @cherrypy.expose
    @require()
    def file(self, ref, name):
        # serve a static file: userid, question ref, file name
        # only works for users running a test
        uid = cherrypy.session.get(SESSION_KEY)
        filename = self.app.get_file(uid, ref, name)
        return cherrypy.lib.static.serve_file(filename)

    # --- ADMIN --------------------------------------------------------------
    @cherrypy.expose
    @require(name_is('0'))
    def admin(self):
        return self.template['admin'].render()

    # --- REVIEW -------------------------------------------------------------
    @cherrypy.expose
    @require(name_is('0'))
    def review(self, test_id):
        fname = self.app.get_json_filename_of_test(test_id)
        try:
            f = open(path.expanduser(fname))
        except FileNotFoundError:
            logging.error('Cannot find "{}" for review.'.format(fname))
        except Exception as e:
            raise e
        else:
            with f:
                t = json.load(f)
                return self.template['review'].render(t=t)
                # FIXME
                # import pdfkit
                # pdfkit.from_string(r, 'out.pdf') # FIXME fails getting css, images, etc

    @cherrypy.expose
    @require(name_is('0'))
    def absfile(self, name):
        filename = path.abspath(path.join(self.app.get_questions_path(), name))
        return cherrypy.lib.static.serve_file(filename)

# ============================================================================
def parse_arguments():
    argparser = argparse.ArgumentParser(description='Server for online tests. Enrolled students and tests have to be previously configured. Please read the documentation included with this software before running the server.')
    serverconf_file = path.normpath(path.join(SERVER_PATH, 'config', 'server.conf'))
    argparser.add_argument('--conf', default=serverconf_file, type=str, help='server configuration file')
    argparser.add_argument('--debug', action='store_true',
        help='Show datastructures when rendering questions')
    argparser.add_argument('--allow-all', action='store_true',
        help='Students are initially allowed to login (can be denied later)')
    argparser.add_argument('testfile', type=str, nargs='+', help='test/exam in YAML format.') # FIXME only one exam supported at the moment
    return argparser.parse_args()

# ============================================================================
if __name__ == '__main__':

    SERVER_PATH = path.dirname(path.realpath(__file__))
    TEMPLATES_DIR = path.join(SERVER_PATH, 'templates')
    LOGGER_CONF = path.join(SERVER_PATH, 'config/logger.yaml')
    SESSION_KEY = 'userid'

    # --- parse command line arguments and build base test
    arg = parse_arguments()

    if arg.debug: # FIXME log.level DEBUG not working
        LOGGER_CONF = path.join(SERVER_PATH, 'config/logger-debug.yaml')
    filename = path.abspath(path.expanduser(arg.testfile[0]))

    # --- Setup logging
    try:
        logging.config.dictConfig(load_yaml(LOGGER_CONF))
    except:
        print('An error ocurred while setting up the logging system.')
        print('Common causes:\n - inexistent directory "logs"?\n - write permission to "logs" directory?')
        sys.exit(1)

    # --- start application
    from app import App

    try:
        app = App(filename, vars(arg))
    except Exception as e:
        logging.critical('Can\'t start application.')
        raise e
        # sys.exit(1)

    # --- create webserver
    webapp = Root(app)
    webapp.adminwebservice = AdminWebService(app)
    webapp.studentwebservice = StudentWebService(app)

    # --- site wide configuration (valid for all apps)
    cherrypy.tools.secureheaders = cherrypy.Tool('before_finalize', secureheaders, priority=60)
    cherrypy.config.update(arg.conf) # configuration file in /config
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.sessions.timeout': 240,  # sessions last 4 hours
            'tools.sessions.storage_type': 'file',  # 'ram' or 'file'
            'tools.sessions.storage_path': 'sessions',  # if storage_type='file'
            # tools.sessions.secure = True
            # tools.sessions.httponly = True

            # Turn on authentication (required for check_auth to work)
            'tools.auth.on': True,

            'tools.secureheaders.on': True,
            'tools.staticdir.root': SERVER_PATH,
        },
        '/adminwebservice': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/studentwebservice': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/static': {
            'tools.auth.on': False,         # everything in /static is public
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'static',# where to get js, css, ...
        },
    }

    cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files) # FIXME what's this?

    # --- Start server
    cherrypy.tree.mount(webapp, script_name='/', config=conf)

    if hasattr(cherrypy.engine, "signal_handler"):
        cherrypy.engine.signal_handler.subscribe()
    if hasattr(cherrypy.engine, "console_control_handler"):
        cherrypy.engine.console_control_handler.subscribe()

    cherrypy.engine.start()
    cherrypy.engine.block()

    # ...App running...

    app.exit()
    # --- Server terminated