# 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/auth/base.py
# class BaseAuthenticator:
#     """Base authenticator class."""
# 
#     def __init__(self):
#         self.state = SQLManager(get_conf())
# 
#     def full_auth(self, username: str, password: str) -> Union[None, User]:  # pylint: disable=too-many-return-statements
#         """This method verifies the username and the password against one of the external auth sources."""
#         user = self.state.user.select(only_one=True, **{"username": username})
#         if user is None or not user.enabled:
#             return None
# 
#         if user.auth_source == "textfile" and PlainTextAuthenticator(get_conf().auth_file).auth(username, password):
#             log.info('User {} authenticated via textfile'.format(user.username))
#             return user
#         elif user.auth_source == "ldap" and LDAPAuthenticator(get_conf(), sasl=False).auth(username, password):
#             log.info('User {} authenticated via ldap'.format(user.username))
#             return user
#         elif user.auth_source == "ldap+sasl" and LDAPAuthenticator(get_conf(), sasl=True).auth(username, password):
#             log.info('User {} authenticated via ldap+sasl'.format(user.username))
#             return user
#         elif user.auth_source == "internal" and user.check_password(password):
#             log.info('User {} authenticated via internal db'.format(user.username))
#             return user
#         elif user.auth_source == "pam" and pam_authenticate(username, password):
#             log.info('User {} authenticated via PAM'.format(user.username))
#             return user
#         else:
#             return None
# 
# 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 os
import subprocess
import zoe_lib.config
from zoe_api.web.request_handler import ZoeWebRequestHandler
from zoe_api.auth.base import BaseAuthenticator
from zoe_api.auth.requests_oauth2 import EurecomGitLabClient
# limitations under the License.

"""Main points of entry for the Zoe web interface."""





class RootWeb(ZoeWebRequestHandler):
    """Handler class"""

    def get(self):
        """Home page without authentication."""
        self.redirect(self.reverse_url("login"))


class LoginWeb(ZoeWebRequestHandler):
    """The login web page."""

    def get(self):
        """Login page."""
        template_vars = {}
        if zoe_lib.config.get_conf().oauth_client_id != '':
            template_vars['with_gitlab_oauth'] = True
        self.render('login.jinja2', **template_vars)

    def post(self):
        """Try to authenticate."""
        login_type = self.get_argument('login', 'userpass')
        if login_type == 'OAUTH':

# 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/auth/base.py
# class BaseAuthenticator:
#     """Base authenticator class."""
# 
#     def __init__(self):
#         self.state = SQLManager(get_conf())
# 
#     def full_auth(self, username: str, password: str) -> Union[None, User]:  # pylint: disable=too-many-return-statements
#         """This method verifies the username and the password against one of the external auth sources."""
#         user = self.state.user.select(only_one=True, **{"username": username})
#         if user is None or not user.enabled:
#             return None
# 
#         if user.auth_source == "textfile" and PlainTextAuthenticator(get_conf().auth_file).auth(username, password):
#             log.info('User {} authenticated via textfile'.format(user.username))
#             return user
#         elif user.auth_source == "ldap" and LDAPAuthenticator(get_conf(), sasl=False).auth(username, password):
#             log.info('User {} authenticated via ldap'.format(user.username))
#             return user
#         elif user.auth_source == "ldap+sasl" and LDAPAuthenticator(get_conf(), sasl=True).auth(username, password):
#             log.info('User {} authenticated via ldap+sasl'.format(user.username))
#             return user
#         elif user.auth_source == "internal" and user.check_password(password):
#             log.info('User {} authenticated via internal db'.format(user.username))
#             return user
#         elif user.auth_source == "pam" and pam_authenticate(username, password):
#             log.info('User {} authenticated via PAM'.format(user.username))
#             return user
#         else:
#             return None
# 
# 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/web/start.py
import os
import subprocess
import zoe_lib.config
from zoe_api.web.request_handler import ZoeWebRequestHandler
from zoe_api.auth.base import BaseAuthenticator
from zoe_api.auth.requests_oauth2 import EurecomGitLabClient

# limitations under the License.

"""Main points of entry for the Zoe web interface."""





class RootWeb(ZoeWebRequestHandler):
    """Handler class"""

    def get(self):
        """Home page without authentication."""
        self.redirect(self.reverse_url("login"))


class LoginWeb(ZoeWebRequestHandler):
    """The login web page."""

    def get(self):
        """Login page."""
        template_vars = {}
        if zoe_lib.config.get_conf().oauth_client_id != '':
            template_vars['with_gitlab_oauth'] = True
        self.render('login.jinja2', **template_vars)

    def post(self):
        """Try to authenticate."""
        login_type = self.get_argument('login', 'userpass')
        if login_type == 'OAUTH':

            egitlab = EurecomGitLabClient(client_id=zoe_lib.config.get_conf().oauth_client_id, client_secret=zoe_lib.config.get_conf().oauth_client_secret, redirect_uri=zoe_lib.config.get_conf().oauth_redirect_uri)