Exemplo n.º 1
0
 def __after__(self):
     c.audit['administrator'] = getUserFromRequest(request).get("login")
     if 'serial' in self.request_params:
         serial = self.request_params['serial']
         c.audit['serial'] = serial
         c.audit['token_type'] = getTokenType(serial)
     audit.log(c.audit)
Exemplo n.º 2
0
 def __after__(self):
     c.audit['administrator'] = getUserFromRequest(request).get("login")
     if 'serial' in self.request_params:
         serial = self.request_params['serial']
         c.audit['serial'] = serial
         c.audit['token_type'] = getTokenType(serial)
     audit.log(c.audit)
Exemplo n.º 3
0
    def __after__(self):

        if c.audit["action"] in ["manage/tokenview_flexi", "manage/userview_flexi"]:
            c.audit["administrator"] = getUserFromRequest(request).get("login")
            if request.params.has_key("serial"):
                c.audit["serial"] = request.params["serial"]
                c.audit["token_type"] = getTokenType(request.params["serial"])

            audit.log(c.audit)
Exemplo n.º 4
0
    def __after__(self):

        if c.audit['action'] in [ 'manage/tokenview_flexi',
                                'manage/userview_flexi' ]:
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            if request.params.has_key('serial'):
                    c.audit['serial'] = request.params['serial']
                    c.audit['token_type'] = getTokenType(request.params['serial'])

            audit.log(c.audit)
Exemplo n.º 5
0
    def __after__(self):

        if c.audit['action'] in [ 'manage/tokenview_flexi',
                                'manage/userview_flexi' ]:
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            if request.params.has_key('serial'):
                    c.audit['serial'] = request.params['serial']
                    c.audit['token_type'] = getTokenType(request.params['serial'])

            audit.log(c.audit)
Exemplo n.º 6
0
    def __call__(self, environ, start_response):
        '''Invoke the Controller'''
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # we add a unique request id to the request enviroment
        # so we can trace individual requests in the logging

        environ['REQUEST_ID'] = str(uuid4())
        environ['REQUEST_START_TIMESTAMP'] = datetime.now()

        with request_context_safety():

            try:
                self._parse_request_params(request)
            except UnicodeDecodeError as exx:
                # we supress Exception here as it will be handled in the
                # controller which will return corresponding response
                log.warning('Failed to access request parameters: %r' % exx)

            self.create_context(request, environ)

            try:
                try:
                    user_desc = getUserFromRequest(request)
                    self.base_auth_user = user_desc.get('login', '')
                except UnicodeDecodeError as exx:
                    # we supress Exception here as it will be handled in the
                    # controller which will return corresponding response
                    log.warning('Failed to identify user due to %r' % exx)

                ret = WSGIController.__call__(self, environ, start_response)
                log.debug("Request reply: %r", ret)

            finally:
                meta.Session.remove()
                # free the lock on the scurityPovider if any
                if self.sep:
                    self.sep.dropSecurityModule()
                closeResolvers()

                # hint for the garbage collector to make the dishes
                data_objects = [
                    "resolvers_loaded", "resolver_clazzes", "linotpConfig",
                    "audit", "hsm"
                ]
                for data_obj in data_objects:
                    if hasattr(c, data_obj):
                        data = getattr(c, data_obj)
                        del data

                log_request_timedelta(log)

            return ret
Exemplo n.º 7
0
    def __after__(self):
        if c.audit['action'] in ['manage/tokenview_flexi',
                                 'manage/userview_flexi' ]:
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            if 'serial' in self.request_params:
                serial = self.request_params['serial']
                c.audit['serial'] = serial
                c.audit['token_type'] = getTokenType(serial)

            c.audit['action_detail'] += linotp.lib.audit.base.get_token_num_info()
            audit.log(c.audit)
Exemplo n.º 8
0
    def __after__(self):
        if c.audit['action'] in ['manage/tokenview_flexi',
                                 'manage/userview_flexi' ]:
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            if 'serial' in self.request_params:
                serial = self.request_params['serial']
                c.audit['serial'] = serial
                c.audit['token_type'] = getTokenType(serial)

            c.audit['action_detail'] += linotp.lib.audit.base.get_token_num_info()
            audit.log(c.audit)
Exemplo n.º 9
0
    def __after__(response):
        '''
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        '''

        g.audit['administrator'] = getUserFromRequest(request).get("login")
        current_app.audit_obj.log(g.audit)

        return response
Exemplo n.º 10
0
def test_JWT_authentifictaion(app):
    authUser = User(
        login="******",
        realm="def_realm",
        resolver_config_identifier="def_resolver",
    )
    with patch("linotp.lib.user.request_context") as mocked_request_context:
        mocked_request_context.get.return_value = authUser

        user = getUserFromRequest()

        assert user.login == "JWT_AUTHENTICATED_USER"
Exemplo n.º 11
0
    def login(self):
        """
        Render the Manage-UI login page
        """
        user = getUserFromRequest()
        if user:
            # user is authenticated, no login required.
            return redirect(url_for(".index"))

        c.debug = current_app.config["DEBUG"]

        return render("manage/login.mako")
Exemplo n.º 12
0
def test_empty_auth(app):
    authUser = User(
        login="",
        realm="",
        resolver_config_identifier="",
    )
    with patch("linotp.lib.user.request_context") as mocked_request_context:
        mocked_request_context.get.return_value = authUser

        user = getUserFromRequest()

        assert user.login == ""
Exemplo n.º 13
0
    def __after__(response):
        """
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        """

        g.audit["administrator"] = getUserFromRequest()
        current_app.audit_obj.log(g.audit)

        return response
Exemplo n.º 14
0
    def __after__(response):
        '''
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        '''

        audit = config.get('audit')

        c.audit['administrator'] = getUserFromRequest(request).get("login")
        audit.log(c.audit)

        return response
Exemplo n.º 15
0
    def __call__(self, environ, start_response):
        '''Invoke the Controller'''
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        path = ""

        with request_context_safety():

            self.create_context(request)

            try:
                if environ:
                    path = environ.get("PATH_INFO", "") or ""

                try:
                    user_desc = getUserFromRequest(request)
                    self.base_auth_user = user_desc.get('login', '')
                except UnicodeDecodeError as exx:
                    # we supress Exception here as it will be handled in the
                    # controller which will return corresponding response
                    log.info('Failed to identify user due to %r' % exx)

                log.debug("request %r" % path)
                ret = WSGIController.__call__(self, environ, start_response)
                log.debug("reply %r" % ret)

            finally:
                meta.Session.remove()
                # free the lock on the scurityPovider if any
                if self.sep:
                    self.sep.dropSecurityModule()
                closeResolvers()

                # hint for the garbage collector to make the dishes
                data_objects = [
                    "resolvers_loaded", "resolver_types", "resolver_clazzes",
                    "linotpConfig", "audit", "hsm"
                ]
                for data_obj in data_objects:
                    if hasattr(c, data_obj):
                        data = getattr(c, data_obj)
                        del data

                log.debug("request %r done!" % path)

            return ret
Exemplo n.º 16
0
    def __after__(self, action):
        """
        """
        try:
            c.audit['administrator'] = getUserFromRequest(request).get('login')

            audit.log(c.audit)
            Session.commit()
            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            return sendError(response, exception, context='after')

        finally:
            Session.close()
Exemplo n.º 17
0
    def __after__(response):
        """
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        """

        g.audit["administrator"] = getUserFromRequest()
        if "serial" in request.params:
            serial = request.params["serial"]
            g.audit["serial"] = serial
            g.audit["token_type"] = getTokenType(serial)

        current_app.audit_obj.log(g.audit)

        return response
Exemplo n.º 18
0
    def __after__(self, action):
        """
        """
        try:
            c.audit['administrator'] = getUserFromRequest(request).get('login')

            audit.log(c.audit)
            Session.commit()
            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            return sendError(response, exception, context='after')

        finally:
            Session.close()
Exemplo n.º 19
0
    def setPassword(self):
        """
        abilty to set password in managed / admin_user resolver
        """
        try:
            old_pw = self.request_params["old_password"]
            new_pw = self.request_params["new_password"]

            authenticated_user = getUserFromRequest()
            username = authenticated_user.login

            if not username:
                raise Exception("Missing authenticated user!")

            sql_url = db.engine.url

            # -------------------------------------------------------------- --

            # the set password handling:
            # any error will raise an excecption which will be displayed
            # to the user

            g.audit["administrator"] = username
            g.audit["info"] = "setPassword"

            set_pw_handler = SetPasswordHandler(DataBaseContext(sql_url))

            set_pw_handler.set_password(username,
                                        old_password=old_pw,
                                        new_password=new_pw)

            g.audit["success"] = True

            return sendResult(
                response,
                obj=True,
                opt={"detail": ("password updated for %r" % username)},
            )

        except Exception as exx:

            g.audit["success"] = False

            log.error(exx)
            db.session.rollback()
            return sendError(response, exx)
Exemplo n.º 20
0
    def __call__(self, environ, start_response):
        '''Invoke the Controller'''
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        path = ""

        with request_context_safety():

            self.create_context(request)

            try:
                if environ:
                    path = environ.get("PATH_INFO", "") or ""

                try:
                    user_desc = getUserFromRequest(request)
                    self.base_auth_user = user_desc.get('login', '')
                except UnicodeDecodeError as exx:
                    # we supress Exception here as it will be handled in the
                    # controller which will return corresponding response
                    log.info('Failed to identify user due to %r' % exx)

                log.debug("request %r" % path)
                ret = WSGIController.__call__(self, environ, start_response)
                log.debug("reply %r" % ret)

            finally:
                meta.Session.remove()
                # free the lock on the scurityPovider if any
                if self.sep:
                    self.sep.dropSecurityModule()
                closeResolvers()

                # hint for the garbage collector to make the dishes
                data_objects = ["resolvers_loaded", "resolver_types",
                                "resolver_clazzes", "linotpConfig", "audit", "hsm"]
                for data_obj in data_objects:
                    if hasattr(c, data_obj):
                        data = getattr(c, data_obj)
                        del data

                log.debug("request %r done!" % path)

            return ret
Exemplo n.º 21
0
    def __after__(response):
        """
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        """

        try:
            g.audit["administrator"] = getUserFromRequest()

            current_app.audit_obj.log(g.audit)
            db.session.commit()  # FIXME: may not be needed
            return response

        except Exception as exception:
            log.error(exception)
            db.session.rollback()
            return sendError(response, exception, context="after")
Exemplo n.º 22
0
    def __after__(self, action):
        """
        """
        params = {}
        try:
            params.update(request.params)
            c.audit['administrator'] = getUserFromRequest(request).get('login')

            audit.log(c.audit)
            Session.commit()
            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            return sendError(response, exception, context='after')

        finally:
            Session.close()
            log.debug('[__after__] done')
Exemplo n.º 23
0
    def __after__(self, action):
        """
        """
        params = {}
        try:
            params.update(request.params)
            c.audit['administrator'] = getUserFromRequest(request).get('login')

            audit.log(c.audit)
            Session.commit()
            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            return sendError(response, exception, context='after')

        finally:
            Session.close()
            log.debug('[__after__] done')
Exemplo n.º 24
0
    def __after__(self, action):
        '''
        '''

        try:
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            c.audit['serial'] = self.request_params.get('serial')

            audit.log(c.audit)
            Session.commit()

            return request

        except Exception as e:
            log.exception(
                "[__after__] unable to create a session cookie: %r" % e)
            Session.rollback()
            return sendError(response, e, context='after')

        finally:
            Session.close()
Exemplo n.º 25
0
    def logout(self):
        """Logs a user out by obliterating their JWT access token
        cookies.
        NOTE: We may wish to block further use of the access token
        in question in case the user has saved a copy somewhere.
        See the Flask-JWT-Extended docs for ideas about how to do this.
        """
        auth_user = getUserFromRequest()
        response = sendResult(
            None, True, opt={"message": f"Logout successful for {auth_user}"})

        unset_jwt_cookies(response)

        # jti: jwt unique identifier
        raw_jwt = get_raw_jwt()
        jti = raw_jwt["jti"]
        expires_at = get_raw_jwt()["exp"]
        expires_in = int(expires_at - datetime.now().timestamp())

        current_app.jwt_blocklist.add_item(jti, expiry=expires_in)
        return response
Exemplo n.º 26
0
    def __after__(response):
        '''
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        '''

        if c.audit['action'] in ['manage/tokenview_flexi',
                                 'manage/userview_flexi' ]:
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            if 'serial' in request.params:
                serial = request.params['serial']
                c.audit['serial'] = serial
                c.audit['token_type'] = getTokenType(serial)

            c.audit['action_detail'] += linotp.lib.audit.base.get_token_num_info()
            audit = config.get('audit')
            audit.log(c.audit)

        return response
Exemplo n.º 27
0
    def __after__(response):
        '''
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        '''

        try:
            g.audit['administrator'] = getUserFromRequest(request).get("login")
            g.audit['serial'] = request.params.get('serial')

            current_app.audit_obj.log(g.audit)
            db.session.commit()
            return response

        except Exception as e:
            log.exception("[__after__] unable to create a session cookie: %r" %
                          e)
            db.session.rollback()
            return sendError(response, e, context='after')
Exemplo n.º 28
0
    def __after__(response):
        '''
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        '''

        try:
            g.audit['administrator'] = getUserFromRequest(request).get('login')

            current_app.audit_obj.log(g.audit)
            db.session.commit()
            return response

        except Exception as exception:
            log.exception(exception)
            db.session.rollback()
            return sendError(response, exception, context='after')

        finally:
            db.session.close()
Exemplo n.º 29
0
    def __after__(response):
        """
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        """

        if g.audit["action"] in [
            "manage/tokenview_flexi",
            "manage/userview_flexi",
        ]:
            g.audit["administrator"] = getUserFromRequest()
            if "serial" in request.params:
                serial = request.params["serial"]
                g.audit["serial"] = serial
                g.audit["token_type"] = getTokenType(serial)

            g.audit[
                "action_detail"
            ] += linotp.lib.audit.base.get_token_num_info()
            current_app.audit_obj.log(g.audit)

        return response
Exemplo n.º 30
0
    def __after__(response):
        '''
        __after__ is called after every action

        :param response: the previously created response - for modification
        :return: return the response
        '''

        audit = config.get('audit')

        try:
            c.audit['administrator'] = getUserFromRequest(request).get('login')

            audit.log(c.audit)
            Session.commit()
            return response

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            return sendError(response, exception, context='after')

        finally:
            Session.close()
Exemplo n.º 31
0
Arquivo: audit.py Projeto: ae-m/LinOTP
 def __after__(self):
     c.audit['administrator'] = getUserFromRequest(request).get("login")
     audit.log(c.audit)
Exemplo n.º 32
0
    def index(self):
        """
        This is the main function of the management web UI
        """

        try:
            c.debug = asbool(config.get("debug", False))
            c.title = "LinOTP Management"
            admin_user = getUserFromRequest(request)
            if admin_user.has_key("login"):
                c.admin = admin_user["login"]

            log.debug("[index] importers: %s" % IMPORT_TEXT)
            c.importers = IMPORT_TEXT
            c.help_url = config.get("help_url")

            ## add render info for token type config
            confs = _getTokenTypeConfig("config")
            token_config_tab = {}
            token_config_div = {}
            for conf in confs:
                tab = ""
                div = ""
                try:
                    # loc = conf +'_token_settings'
                    tab = confs.get(conf).get("title")
                    # tab = '<li ><a href=#'+loc+'>'+tab+'</a></li>'

                    div = confs.get(conf).get("html")
                    # div = +div+'</div>'
                except Exception as e:
                    log.debug("[index] no config info for token type %s  (%r)" % (conf, e))

                if tab is not None and div is not None and len(tab) > 0 and len(div) > 0:
                    token_config_tab[conf] = tab
                    token_config_div[conf] = div

            c.token_config_tab = token_config_tab
            c.token_config_div = token_config_div

            ##  add the enrollment fragments from the token definition
            ##  tab: <option value="ocra">${_("OCRA - challenge/response Token")}</option>
            ##  div: "<div id='"+ tt + "'>"+enroll+"</div>"
            enrolls = _getTokenTypeConfig("init")

            token_enroll_tab = {}
            token_enroll_div = {}
            for conf in enrolls:
                tab = ""
                div = ""
                try:
                    tab = enrolls.get(conf).get("title")
                    div = enrolls.get(conf).get("html")
                except Exception as e:
                    log.debug("[index] no enrollment info for token type %s  (%r)" % (conf, e))

                if tab is not None and div is not None and len(tab) > 0 and len(div) > 0:
                    token_enroll_tab[conf] = tab
                    token_enroll_div[conf] = div

            c.token_enroll_tab = token_enroll_tab
            c.token_enroll_div = token_enroll_div

            c.tokentypes = _getTokenTypes()

            http_host = request.environ.get("HTTP_HOST")
            url_scheme = request.environ.get("wsgi.url_scheme")
            c.logout_url = "%s://log-me-out:fake@%s/manage/logout" % (url_scheme, http_host)

            Session.commit()
            ren = render("/manage/manage-base.mako")
            return ren

        except PolicyException as pe:
            log.error("[index] Error during checking policies: %r" % pe)
            log.error("[index] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, unicode(pe), 1)

        except Exception as ex:
            log.error("[index] failed! %r" % ex)
            log.error("[index] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, ex)

        finally:
            Session.close()
            log.debug("[index] done")
Exemplo n.º 33
0
    def create_context(self, request):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        self.request_context = {}
        self.request_context['Config'] = linotp_config
        self.request_context['Policies'] = getPolicies(config=linotp_config)
        self.request_context['translate'] = translate

        request_params = {}

        try:
            request_params.update(request.params)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['Params'] = request_params

        authUser = None
        try:
            authUser = getUserFromRequest(request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['AuthUser'] = authUser

        requestUser = None
        try:
            requestUser = getUserFromParam(request_params, True)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)
        self.request_context['RequestUser'] = requestUser

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['Client'] = client

        self.request_context['audit'] = {}

        defaultRealm = ""
        try:
            defaultRealm = getDefaultRealm(linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['defaultRealm'] = defaultRealm

        realms = None
        try:
            realms = getRealms(context=self.request_context)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        self.request_context['Realms'] = realms

        return
Exemplo n.º 34
0
Arquivo: ocra.py Projeto: hopil/LinOTP
    def __after__(self):
        c.audit["administrator"] = getUserFromRequest(request).get("login")
        audit.log(c.audit)

        return response
Exemplo n.º 35
0
    def create_context(self, request):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        request_context['Config'] = linotp_config
        request_context['Policies'] = getPolicies()
        request_context['translate'] = translate

        initResolvers()

        request_params = {}

        try:
            request_params.update(request.params)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['Params'] = request_params

        authUser = None
        try:
            authUser = getUserFromRequest(request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['AuthUser'] = authUser

        requestUser = None
        try:
            requestUser = getUserFromParam(request_params, True)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)
        request_context['RequestUser'] = requestUser

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['Client'] = client

        request_context['Audit'] = Audit
        request_context['audit'] = Audit.initialize(request,
                                                         client=client)

        defaultRealm = ""
        try:
            defaultRealm = getDefaultRealm(linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['defaultRealm'] = defaultRealm

        realms = None
        try:
            realms = getRealms()
        except UnicodeDecodeError as exx:
            log.error("Faild to decode request parameters %r" % exx)

        request_context['Realms'] = realms

        request_context['hsm'] = None
        if hasattr(self, "hsm"):
            request_context['hsm'] = self.hsm

        # copy some system entries from pylons
        syskeys = {
                   "radius.nas_identifier": "LinOTP",
                   "radius.dictfile": "/etc/linotp2/dictionary"
        }

        sysconfig = {}
        for key, default in syskeys.items():
            try:
                sysconfig[key] = config.get(key, default)
            except:
                log.info('no sytem config entry %s' % key)

        request_context['SystemConfig'] = sysconfig
Exemplo n.º 36
0
 def __after__(self):
     c.audit["administrator"] = getUserFromRequest(request).get("login")
     if request.params.has_key("serial"):
         c.audit["serial"] = request.params["serial"]
         c.audit["token_type"] = getTokenType(request.params["serial"])
     audit.log(c.audit)
Exemplo n.º 37
0
 def __after__(self):
     c.audit['administrator'] = getUserFromRequest(request).get("login")
     if request.params.has_key('serial'):
             c.audit['serial'] = request.params['serial']
             c.audit['token_type'] = getTokenType(request.params['serial'])
     audit.log(c.audit)
Exemplo n.º 38
0
 def run_and_assert(self, request):
     authentification = getUserFromRequest(request)
     self.assertEqual(authentification['login'], self.login,
                      'Input was: %r' % request.environ)
     return authentification
Exemplo n.º 39
0
 def test_empty_auth(self):
     request = self.Request({})
     authentification = getUserFromRequest(request)
     self.assertEqual(authentification['login'], '', 'Input was empty')
Exemplo n.º 40
0
    def index(self):
        '''
        This is the main function of the management web UI
        '''

        try:
            c.debug = asbool(config.get('debug', False))
            c.title = "LinOTP Management"
            admin_user = getUserFromRequest(request)
            if admin_user.has_key('login'):
                # Get a list of their allowed admin realms.
                # Set their current realm to the first one in the list.
                c.login = admin_user['login']
                realms = getAdminRealms(c.login)
                if (realms):
                    c.realm = realms[0]
                else:
                    realm = getDefaultRealm()

                c.admin = "%s@%s" % (c.login, c.realm)

            log.debug("[index] importers: %s" % IMPORT_TEXT)
            c.importers = IMPORT_TEXT
            c.help_url = config.get('help_url')

            ## add render info for token type config
            confs = _getTokenTypeConfig('config')
            token_config_tab = {}
            token_config_div = {}
            for conf in confs:
                tab = ''
                div = ''
                try:
                    #loc = conf +'_token_settings'
                    tab = confs.get(conf).get('title')
                    #tab = '<li ><a href=#'+loc+'>'+tab+'</a></li>'

                    div = confs.get(conf).get('html')
                    #div = +div+'</div>'
                except Exception as e:
                    log.debug('[index] no config info for token type %s  (%r)' % (conf, e))

                if tab is not None and div is not None and len(tab) > 0 and len(div) > 0:
                    token_config_tab[conf] = tab
                    token_config_div[conf] = div

            c.token_config_tab = token_config_tab
            c.token_config_div = token_config_div

            ##  add the enrollment fragments from the token definition
            ##  tab: <option value="ocra">${_("OCRA - challenge/response Token")}</option>
            ##  div: "<div id='"+ tt + "'>"+enroll+"</div>"
            enrolls = _getTokenTypeConfig('init')

            token_enroll_tab = {}
            token_enroll_div = {}
            for conf in enrolls:
                tab = ''
                div = ''
                try:
                    tab = enrolls.get(conf).get('title')
                    div = enrolls.get(conf).get('html')
                except Exception as e:
                    log.debug('[index] no enrollment info for token type %s  (%r)' % (conf, e))

                if tab is not None and div is not None and len(tab) > 0 and len(div) > 0:
                    token_enroll_tab[conf] = tab
                    token_enroll_div[conf] = div

            c.token_enroll_tab = token_enroll_tab
            c.token_enroll_div = token_enroll_div

            c.tokentypes = _getTokenTypes()

            http_host = request.environ.get("HTTP_HOST")
            url_scheme = request.environ.get("wsgi.url_scheme")
            # Use WebAuth to logout instead of Apache.
            c.logout_url = "%s://%s/account/logout" % (url_scheme, http_host)

            Session.commit()
            ren = render('/manage/manage-base.mako')
            return ren

        except PolicyException as pe:
            log.error("[index] Error during checking policies: %r" % pe)
            log.error("[index] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, unicode(pe), 1)

        except Exception as ex:
            log.error("[index] failed! %r" % ex)
            log.error("[index] %s" % traceback.format_exc())
            Session.rollback()
            return sendError(response, ex)

        finally:
            Session.close()
            log.debug('[index] done')
Exemplo n.º 41
0
    def index(self):
        '''
        This is the main function of the management web UI
        '''

        try:
            c.debug = asbool(config.get('debug', False))
            c.title = "LinOTP Management"
            admin_user = getUserFromRequest(request)

            if admin_user.has_key('login'):
                c.admin = admin_user['login']

            log.debug("[index] importers: %s" % IMPORT_TEXT)
            c.importers = IMPORT_TEXT
            c.help_url = config.get('help_url')

            # -------------------------------------------------------------- --

            # check for support of setting admin password

            c.admin_can_change_password = False
            if ('linotpadmin.user' in config and
                'linotpadmin.password' in config):
                c.admin_can_change_password = True

            # -------------------------------------------------------------- --

            # add render info for token type config
            confs = _getTokenTypeConfig('config')
            token_config_tab = {}
            token_config_div = {}
            for conf in confs:
                tab = ''
                div = ''
                try:
                    # loc = conf +'_token_settings'
                    tab = confs.get(conf).get('title')
                    # tab = '<li ><a href=#'+loc+'>'+tab+'</a></li>'

                    div = confs.get(conf).get('html')
                    # div = +div+'</div>'
                except Exception as e:
                    log.debug('[index] no config info for token type %s  (%r)' % (conf, e))

                if tab is not None and div is not None and len(tab) > 0 and len(div) > 0:
                    token_config_tab[conf] = tab
                    token_config_div[conf] = div

            c.token_config_tab = token_config_tab
            c.token_config_div = token_config_div

            #  add the enrollment fragments from the token definition
            #  tab: <option value="ocra">${_("OCRA - challenge/response Token")}</option>
            #  div: "<div id='"+ tt + "'>"+enroll+"</div>"
            enrolls = _getTokenTypeConfig('init')

            token_enroll_tab = {}
            token_enroll_div = {}
            for conf in enrolls:
                tab = ''
                div = ''
                try:
                    tab = enrolls.get(conf).get('title')
                    div = enrolls.get(conf).get('html')
                except Exception as e:
                    log.debug('[index] no enrollment info for token type %s  (%r)' % (conf, e))

                if tab is not None and div is not None and len(tab) > 0 and len(div) > 0:
                    token_enroll_tab[conf] = tab
                    token_enroll_div[conf] = div

            c.token_enroll_tab = token_enroll_tab
            c.token_enroll_div = token_enroll_div

            c.tokentypes = _getTokenTypes()

            # Use HTTP_X_FORWARDED_HOST in preference to HTTP_HOST
            # in case we're running behind a reverse proxy
            http_host = request.environ.get("HTTP_X_FORWARDED_HOST", '')
            if not http_host:
                http_host = request.environ.get("HTTP_HOST")
            url_scheme = request.environ.get("wsgi.url_scheme")
            c.logout_url = "%s://log-me-out:fake@%s/manage/logout" % (url_scheme, http_host)

            Session.commit()
            ren = render('/manage/manage-base.mako')
            return ren

        except PolicyException as pe:
            log.exception("[index] Error during checking policies: %r" % pe)
            Session.rollback()
            return sendError(response, unicode(pe), 1)

        except Exception as ex:
            log.exception("[index] failed! %r" % ex)
            Session.rollback()
            return sendError(response, ex)

        finally:
            Session.close()