# Path: zoe_api/rest_api/request_handler.py
# 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:
#             self.set_status(e.status_code, "Unauthorized access: {}".format(e))
#             return None
#         return user
# 
# Path: zoe_api/web/request_handler.py
# class ZoeWebRequestHandler(ZoeRequestHandler):
#     """RequestHandler class for Zoe Web interface."""
# 
#     def initialize(self, **kwargs):
#         """Initialize the Jinja template system."""
#         super().initialize(**kwargs)
#         if 'jinja_environment' not in self.application.settings:
#             raise RuntimeError("Needs jinja2 Environment. Initialize with JinjaApp.init_app first")
#         else:
#             self._jinja_env = self.application.settings['jinja_environment']
# 
#     def _render(self, template, **kwargs):
#         """ todo: support multiple template preprocessors """
# 
#         ctx = {
#             'request': self.request,
#             'path_args': self.path_args,
#             'path_kwargs': self.path_kwargs,
#             'settings': self.application.settings,
#             'reverse_url': self.application.reverse_url,
#             'static_url': self.static_url,
#             'xsrf_form_html': self.xsrf_form_html,
#             'datetime': datetime,
#             'locale': self.locale,
#             'handler': self,
#             'zoe_version': zoe_lib.version.ZOE_VERSION,
#             'server_address': self.request.host,
#         }
# 
#         try:
#             ctx['user'] = super().get_current_user()
#         except ZoeAuthException:
#             pass
# 
#         ctx.update(kwargs)
#         return template.render(ctx)
# 
#     def render(self, template_name, **kwargs):
#         """ renders a template file. """
#         template = self._jinja_env.get_template(template_name)
#         try:
#             html = self._render(template, **kwargs)
#         except TemplateSyntaxError as e:
#             self.error_page('Template syntax error at {}:{}:<br> {}'.format(e.name, e.lineno, e.message), 500)
#             return
#         except Exception as e:
#             log.exception('Jinja2 exception while rendering the template {}'.format(template_name))
#             self.error_page('Jinja2 template exception: {}'.format(e), 500)
#             return
#         self.finish(html)
# 
#     def render_string(self, source, **kwargs):
#         """ renders a template source string. """
#         template = self._jinja_env.from_string(source)
#         return self._render(template, **kwargs)
# 
#     def get_current_user(self):
#         """In case auth fails, redirect to login page."""
#         try:
#             user = super().get_current_user()
#         except ZoeAuthException as e:
#             with_gitlab_oauth = zoe_lib.config.get_conf().oauth_client_id != ''
#             self.render('login.jinja2', error=e.message, with_gitlab_oauth=with_gitlab_oauth)
#             return None
#         return user
# 
#     def error_page(self, error_message: str, status: int = 400):
#         """Generate an error page."""
#         self.set_status(status)
#         self.render('error.jinja2', error=error_message)
# 
# 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/auth/requests_oauth2/services.py
# class EurecomGitLabClient(OAuth2):
#     """GitLab oauth2"""
#     site = "https://gitlab.eurecom.fr"
#     authorization_url = "/oauth/authorize"
#     token_url = "/oauth/token"
#     userinfo_url = site + '/oauth/userinfo'
#     scope_sep = " "


import logging
import os
import requests
import tornado.escape
import zoe_lib.config
from zoe_api.rest_api.request_handler import ZoeAPIRequestHandler
from zoe_api.web.request_handler import ZoeWebRequestHandler
from zoe_api.exceptions import ZoeException
from zoe_api.auth.requests_oauth2 import EurecomGitLabClient

"""The User API endpoints."""





log = logging.getLogger(__name__)


class UserAPI(ZoeAPIRequestHandler):
    """The User API endpoint. Ops on a single user."""

    def get(self, user_id):
        """HTTP GET method."""
        if self.current_user is None:
            return

        try:
            user_id = int(user_id)
        except ValueError:
            self.set_status(400, "Parameter must be an integer")

        if user_id == self.current_user.id:
            ret = {
                'user': self.current_user.serialize()
            }
        else:
            try:
                user = self.api_endpoint.user_by_id(self.current_user, user_id)

# Path: zoe_api/rest_api/request_handler.py
# 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:
#             self.set_status(e.status_code, "Unauthorized access: {}".format(e))
#             return None
#         return user
# 
# Path: zoe_api/web/request_handler.py
# class ZoeWebRequestHandler(ZoeRequestHandler):
#     """RequestHandler class for Zoe Web interface."""
# 
#     def initialize(self, **kwargs):
#         """Initialize the Jinja template system."""
#         super().initialize(**kwargs)
#         if 'jinja_environment' not in self.application.settings:
#             raise RuntimeError("Needs jinja2 Environment. Initialize with JinjaApp.init_app first")
#         else:
#             self._jinja_env = self.application.settings['jinja_environment']
# 
#     def _render(self, template, **kwargs):
#         """ todo: support multiple template preprocessors """
# 
#         ctx = {
#             'request': self.request,
#             'path_args': self.path_args,
#             'path_kwargs': self.path_kwargs,
#             'settings': self.application.settings,
#             'reverse_url': self.application.reverse_url,
#             'static_url': self.static_url,
#             'xsrf_form_html': self.xsrf_form_html,
#             'datetime': datetime,
#             'locale': self.locale,
#             'handler': self,
#             'zoe_version': zoe_lib.version.ZOE_VERSION,
#             'server_address': self.request.host,
#         }
# 
#         try:
#             ctx['user'] = super().get_current_user()
#         except ZoeAuthException:
#             pass
# 
#         ctx.update(kwargs)
#         return template.render(ctx)
# 
#     def render(self, template_name, **kwargs):
#         """ renders a template file. """
#         template = self._jinja_env.get_template(template_name)
#         try:
#             html = self._render(template, **kwargs)
#         except TemplateSyntaxError as e:
#             self.error_page('Template syntax error at {}:{}:<br> {}'.format(e.name, e.lineno, e.message), 500)
#             return
#         except Exception as e:
#             log.exception('Jinja2 exception while rendering the template {}'.format(template_name))
#             self.error_page('Jinja2 template exception: {}'.format(e), 500)
#             return
#         self.finish(html)
# 
#     def render_string(self, source, **kwargs):
#         """ renders a template source string. """
#         template = self._jinja_env.from_string(source)
#         return self._render(template, **kwargs)
# 
#     def get_current_user(self):
#         """In case auth fails, redirect to login page."""
#         try:
#             user = super().get_current_user()
#         except ZoeAuthException as e:
#             with_gitlab_oauth = zoe_lib.config.get_conf().oauth_client_id != ''
#             self.render('login.jinja2', error=e.message, with_gitlab_oauth=with_gitlab_oauth)
#             return None
#         return user
# 
#     def error_page(self, error_message: str, status: int = 400):
#         """Generate an error page."""
#         self.set_status(status)
#         self.render('error.jinja2', error=error_message)
# 
# 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/auth/requests_oauth2/services.py
# class EurecomGitLabClient(OAuth2):
#     """GitLab oauth2"""
#     site = "https://gitlab.eurecom.fr"
#     authorization_url = "/oauth/authorize"
#     token_url = "/oauth/token"
#     userinfo_url = site + '/oauth/userinfo'
#     scope_sep = " "


# Path: zoe_api/rest_api/user.py
import logging
import os
import requests
import tornado.escape
import zoe_lib.config
from zoe_api.rest_api.request_handler import ZoeAPIRequestHandler
from zoe_api.web.request_handler import ZoeWebRequestHandler
from zoe_api.exceptions import ZoeException
from zoe_api.auth.requests_oauth2 import EurecomGitLabClient


"""The User API endpoints."""





log = logging.getLogger(__name__)


class UserAPI(ZoeAPIRequestHandler):
    """The User API endpoint. Ops on a single user."""

    def get(self, user_id):
        """HTTP GET method."""
        if self.current_user is None:
            return

        try:
            user_id = int(user_id)
        except ValueError:
            self.set_status(400, "Parameter must be an integer")

        if user_id == self.current_user.id:
            ret = {
                'user': self.current_user.serialize()
            }
        else:
            try:
                user = self.api_endpoint.user_by_id(self.current_user, user_id)

            except ZoeException as e: