# Path: zoe_api/custom_request_handler.py
# class ZoeRequestHandler(tornado.web.RequestHandler):
#     """Customized request handler."""
# 
#     def initialize(self, **kwargs):
#         """Initializes the request handler."""
#         super().initialize()
#         self.api_endpoint = kwargs['api_endpoint']  # type: APIEndpoint
# 
#     def get_current_user(self):
#         """Get the user making the request from one of several possible locations."""
#         auth_header = self.request.headers.get('Authorization')
#         if self.get_secure_cookie('zoe'):  # cookie auth
#             username = tornado.escape.xhtml_escape(self.get_secure_cookie('zoe'))
#             user = self.api_endpoint.user_by_name(username)
#         elif auth_header is not None and auth_header.startswith('Basic '):  # basic auth
#             auth_decoded = base64.decodebytes(bytes(auth_header[6:], 'ascii')).decode('utf-8')
#             username, password = auth_decoded.split(':', 2)
#             user = BaseAuthenticator().full_auth(username, password)
#         else:
#             user = None
# 
#         if user is None:
#             raise ZoeAuthException('Invalid username or password')
#         if not user.enabled:
#             raise ZoeAuthException('User has been disabled by the administrator')
# 
#         return user
# 
#     def on_finish(self):
#         """Log request."""
#         try:
#             user = ZoeRequestHandler.get_current_user(self)
#         except ZoeAuthException:
#             user = "not authenticated"
#         log.info("{} {} {} ({}, {}) {:.2f}ms".format(self.get_status(), self.request.method, self.request.path, self.request.remote_ip, user, self.request.request_time()))
# 
#     def data_received(self, chunk):
#         """Not implemented as we do not use stream uploads"""
# 
# Path: zoe_api/exceptions.py
# class ZoeException(Exception):
#     """
#     A generic exception.
#     """
#     def __init__(self, message='Something happened'):
#         super().__init__()
#         self.message = message
#         self.status_code = 500
# 
#     def __str__(self):
#         return '{}: {}'.format(self.status_code, self.message)


import logging
from zoe_api.custom_request_handler import ZoeRequestHandler
from zoe_api.exceptions import ZoeException
log = logging.getLogger(__name__)


class ZoeAPIRequestHandler(ZoeRequestHandler):
    """RequestHandler class for Zoe Web interface."""

    def set_default_headers(self):
        """Set up the headers for enabling CORS."""
        self._manage_cors_headers()

    def _manage_cors_headers(self):
        """Set up the headers for enabling CORS."""
        if self.request.headers.get('Origin') is None:
            self.set_header("Access-Control-Allow-Origin", "*")
        else:
            self.set_header("Access-Control-Allow-Origin", self.request.headers.get('Origin'))
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with, Content-Type, origin, authorization, accept, client-security-token")
        self.set_header("Access-Control-Allow-Methods", "OPTIONS, GET, DELETE")
        self.set_header("Access-Control-Max-Age", "1000")

    def options(self):
        """Needed for CORS."""
        self.set_status(204)
        self.finish()

    def get_current_user(self):
        """In case auth fails, redirect to login page."""
        try:
            user = super().get_current_user()

# Path: zoe_api/custom_request_handler.py
# class ZoeRequestHandler(tornado.web.RequestHandler):
#     """Customized request handler."""
# 
#     def initialize(self, **kwargs):
#         """Initializes the request handler."""
#         super().initialize()
#         self.api_endpoint = kwargs['api_endpoint']  # type: APIEndpoint
# 
#     def get_current_user(self):
#         """Get the user making the request from one of several possible locations."""
#         auth_header = self.request.headers.get('Authorization')
#         if self.get_secure_cookie('zoe'):  # cookie auth
#             username = tornado.escape.xhtml_escape(self.get_secure_cookie('zoe'))
#             user = self.api_endpoint.user_by_name(username)
#         elif auth_header is not None and auth_header.startswith('Basic '):  # basic auth
#             auth_decoded = base64.decodebytes(bytes(auth_header[6:], 'ascii')).decode('utf-8')
#             username, password = auth_decoded.split(':', 2)
#             user = BaseAuthenticator().full_auth(username, password)
#         else:
#             user = None
# 
#         if user is None:
#             raise ZoeAuthException('Invalid username or password')
#         if not user.enabled:
#             raise ZoeAuthException('User has been disabled by the administrator')
# 
#         return user
# 
#     def on_finish(self):
#         """Log request."""
#         try:
#             user = ZoeRequestHandler.get_current_user(self)
#         except ZoeAuthException:
#             user = "not authenticated"
#         log.info("{} {} {} ({}, {}) {:.2f}ms".format(self.get_status(), self.request.method, self.request.path, self.request.remote_ip, user, self.request.request_time()))
# 
#     def data_received(self, chunk):
#         """Not implemented as we do not use stream uploads"""
# 
# Path: zoe_api/exceptions.py
# class ZoeException(Exception):
#     """
#     A generic exception.
#     """
#     def __init__(self, message='Something happened'):
#         super().__init__()
#         self.message = message
#         self.status_code = 500
# 
#     def __str__(self):
#         return '{}: {}'.format(self.status_code, self.message)


# Path: zoe_api/rest_api/request_handler.py
import logging
from zoe_api.custom_request_handler import ZoeRequestHandler
from zoe_api.exceptions import ZoeException

log = logging.getLogger(__name__)


class ZoeAPIRequestHandler(ZoeRequestHandler):
    """RequestHandler class for Zoe Web interface."""

    def set_default_headers(self):
        """Set up the headers for enabling CORS."""
        self._manage_cors_headers()

    def _manage_cors_headers(self):
        """Set up the headers for enabling CORS."""
        if self.request.headers.get('Origin') is None:
            self.set_header("Access-Control-Allow-Origin", "*")
        else:
            self.set_header("Access-Control-Allow-Origin", self.request.headers.get('Origin'))
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Headers", "x-requested-with, Content-Type, origin, authorization, accept, client-security-token")
        self.set_header("Access-Control-Allow-Methods", "OPTIONS, GET, DELETE")
        self.set_header("Access-Control-Max-Age", "1000")

    def options(self):
        """Needed for CORS."""
        self.set_status(204)
        self.finish()

    def get_current_user(self):
        """In case auth fails, redirect to login page."""
        try:
            user = super().get_current_user()

        except ZoeException as e: