示例#1
0
    def __before__(self, action, **params):
        '''
        Here we see, what action is to be called and check the authorization
        '''

        try:

            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)
            if action != "check_t":
                check_session(request)

            request_context['Audit'] = audit
            return response

        except webob.exc.HTTPUnauthorized as acc:

            # the exception, when an abort() is called if forwarded

            log.exception("[__before__::%r] webob.exception %r"
                          % (action, acc))

            Session.rollback()
            Session.close()
            raise acc

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')
示例#2
0
    def __before__(self, action, **params):
        """
        """
        try:
            log.debug('[__before__::%r] %r', action, params)


            c.audit = request_context['audit']
            c.audit['success'] = False

            c.audit['client'] = get_client(request)

            # Session handling
            check_session(request)

            request_context['Audit'] = audit
            checkAuthorisation(scope='monitoring', method=action)

            return request

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

        finally:
            log.debug('[__before__::%r] done', action)
示例#3
0
    def __before__(self, action, **params):
        """
        """
        try:
            log.debug('[__before__::%r] %r', action, params)

            audit.initialize()
            c.audit['success'] = False

            c.audit['client'] = get_client(request)

            # Session handling
            check_session(request)

            self.request_context['Audit'] = audit

            return request

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

        finally:
            log.debug('[__before__::%r] done', action)
示例#4
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context['action']

        try:

            c.audit = request_context['audit']
            c.audit['success'] = False

            c.audit['client'] = get_client(request)

            # Session handling
            check_session(request)

            audit = config.get('audit')
            request_context['Audit'] = audit
            checkAuthorisation(scope='monitoring', method=action)

            return

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            Session.close()
            return sendError(response, exception, context='before')
示例#5
0
    def __before__(self, action, **params):
        '''
        Here we see, what action is to be called and check the authorization
        '''

        log.debug("[__before__::%r] %r" % (action, params))

        try:

            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)
            if action != "check_t":
                check_session(request)

            request_context['Audit'] = audit
            return response

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.exception("[__before__::%r] webob.exception %r" % (action, acc))
            Session.rollback()
            Session.close()
            raise acc

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#6
0
    def __before__(self, action, **params):
        '''
        Here we see, what action is to be called and check the authorization
        '''

        log.debug("[__before__::%r] %r" % (action, params))

        try:

            audit.initialize()
            c.audit['success'] = False
            c.audit['client'] = get_client()
            if action != "check_t":
                check_session()

            return response

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.error("[__before__::%r] webob.exception %r" % (action, acc))
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            raise acc

        except Exception as exx:
            log.error("[__before__::%r] exception %r" % (action, exx))
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#7
0
    def __before__(self, action, **params):
        """
        """
        try:
            log.debug('[__before__::%r] %r', action, params)

            c.audit = request_context['audit']
            c.audit['success'] = False

            c.audit['client'] = get_client(request)

            # Session handling
            check_session(request)

            request_context['Audit'] = audit
            checkAuthorisation(scope='monitoring', method=action)

            return request

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

        finally:
            log.debug('[__before__::%r] done', action)
示例#8
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            audit.initialize()
            c.audit['success'] = False
            c.audit['client'] = get_client(request)

            c.version = get_version()
            c.licenseinfo = get_copyright_info()
            c.polDefs = getPolicyDefinitions()

            # Session handling for the functions, that show data:
            # Also exclude custom-style.css, since the CSRF check
            # will always fail and return a HTTP 401 anyway.
            # A HTTP 404 makes more sense.
            if request.path.lower() in [
                    '/manage/', '/manage', '/manage/logout',
                    '/manage/audittrail', '/manage/policies',
                    '/manage/tokenview', '/manage/userview', '/manage/help',
                    '/manage/custom-style.css'
            ]:
                pass
            else:
                check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#9
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context["action"]

        try:

            g.audit["success"] = False

            g.audit["client"] = get_client(request)

            # Session handling
            check_session(request)

            audit = config.get("audit")
            request_context["Audit"] = audit
            checkAuthorisation(scope="monitoring", method=action)

            return

        except Exception as exception:
            log.error(exception)
            db.session.rollback()
            return sendError(response, exception, context="before")
示例#10
0
文件: ocra.py 项目: hopil/LinOTP
    def __before__(self, action, **params):
        """
        Here we see, what action is to be called and check the authorization
        """

        log.debug("[__before__::%r] %r" % (action, params))

        try:

            audit.initialize()
            c.audit["success"] = False
            c.audit["client"] = get_client()
            if action != "check_t":
                check_session()

            return response

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.exception("[__before__::%r] webob.exception %r" % (action, acc))
            Session.rollback()
            Session.close()
            raise acc

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context="before")

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#11
0
    def __before__(self, action, **params):
        """
        """
        try:
            log.debug('[__before__::%r] %r', action, params)

            audit.initialize()
            c.audit['success'] = False

            c.audit['client'] = get_client(request)

            # Session handling
            check_session(request)

            self.request_context['Audit'] = audit

            return request

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

        finally:
            log.debug('[__before__::%r] done', action)
示例#12
0
文件: manage.py 项目: smartree/LinOTP
    def __before__(self, **params):
        """
        __before__ is called before every action

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context['action']

        try:
            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)

            c.version = get_version()
            c.version_ref = base64.encodebytes(c.version.encode())[:6]

            c.licenseinfo = get_copyright_info()
            c.polDefs = getPolicyDefinitions()

            c.display_provider = boolean(
                    request_context['Config'].get('display_provider', True))

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

            # 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

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

            # Session handling for the functions, that show data:
            # Also exclude custom-style.css, since the CSRF check
            # will always fail and return a HTTP 401 anyway.
            # A HTTP 404 makes more sense.
            if request.path.lower() in ['/manage/', '/manage',
                                        '/manage/logout',
                                        '/manage/audittrail',
                                        '/manage/policies',
                                        '/manage/tokenview',
                                        '/manage/userview',
                                        '/manage/help',
                                        '/manage/custom-style.css']:
                pass
            else:
                check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#13
0
    def __before__(self, action):

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r", action, exx)
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')
示例#14
0
    def __before__(self, action):

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r", action, exx)
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')
示例#15
0
    def __before__(self, action, **params):

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            request_context['Audit'] = audit
            return response

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')
示例#16
0
    def __before__(self, action, **params):

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            request_context['Audit'] = audit
            return response

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')
示例#17
0
    def __before__(self, action, **params):

        try:
            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)

            c.version = get_version()
            c.version_ref = base64.encodestring(c.version)[:6]

            c.licenseinfo = get_copyright_info()
            c.polDefs = getPolicyDefinitions()

            c.display_provider = boolean(
                    request_context['Config'].get('display_provider', True))

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

            # 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

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

            # Session handling for the functions, that show data:
            # Also exclude custom-style.css, since the CSRF check
            # will always fail and return a HTTP 401 anyway.
            # A HTTP 404 makes more sense.
            if request.path.lower() in ['/manage/', '/manage',
                                        '/manage/logout',
                                        '/manage/audittrail',
                                        '/manage/policies',
                                        '/manage/tokenview',
                                        '/manage/userview',
                                        '/manage/help',
                                        '/manage/custom-style.css']:
                pass
            else:
                check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#18
0
文件: validate.py 项目: hopil/LinOTP
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            audit.initialize()
            c.audit['client'] = get_client()
            return response

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#19
0
    def __before__(self, action):

        log.debug("[__before__]")

        try:
            audit.initialize()
            c.audit['client'] = get_client(request)
            check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#20
0
    def __before__(self, action):

        log.debug("[__before__]")

        try:
            c.audit = self.request_context['audit']
            c.audit['client'] = get_client(request)
            check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#21
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context["action"]

        try:
            g.audit["client"] = get_client(request)
            check_session(request)
        except Exception as exx:
            log.error("[__before__::%r] exception %r", action, exx)
            db.session.rollback()
            return sendError(response, exx, context="before")
示例#22
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError
        """

        action = request_context['action']

        try:
            g.audit['client'] = get_client(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            db.session.rollback()
            return sendError(response, exx, context='before')
示例#23
0
文件: audit.py 项目: rb12345/LinOTP
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            check_session(request)
            request_context['Audit'] = audit

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#24
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            audit.initialize()
            c.audit["client"] = get_client()
            return response

        except Exception as exx:
            log.error("[__before__::%r] exception %r" % (action, exx))
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, exx, context="before")

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#25
0
文件: gettoken.py 项目: RDLM-01/Elm
    def __before__(self, action, **params):

        log.debug("[__before__]")

        try:
            audit.initialize()
            c.audit['client'] = get_client()
            check_session()

        except Exception as exx:
            log.error("[__before__::%r] exception %r" % (action, exx))
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#26
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            if request_context: # XXX why this check?
                request_context['Audit'] = audit
            return response

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#27
0
    def __before__(self, **params):
        '''
        '''

        action = request_context['action']

        try:

            g.audit['success'] = False
            g.audit['client'] = get_client(request)

            # Session handling
            if action not in ['getsession', 'dropsession']:
                check_session(request, scope='helpdesk')

        except Exception as exx:
            log.exception("[__before__::%r] exception", action)

            db.session.rollback()
            return sendError(None, exx, context='before')
示例#28
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        Here we see, what action is to be called and check the authorization

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context['action']

        try:

            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)
            if action != "check_t":
                check_session(request)

            audit = config.get('audit')
            request_context['Audit'] = audit
            return

        except flap.HTTPUnauthorized as acc:

            # the exception, when an abort() is called if forwarded

            log.exception("[__before__::%r] webob.exception %r" %
                          (action, acc))

            Session.rollback()
            Session.close()
            raise acc

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')
示例#29
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            audit.initialize()
            c.audit["success"] = False
            c.audit["client"] = get_client()

            c.version = get_version()
            c.licenseinfo = get_copyright_info()
            c.polDefs = getPolicyDefinitions()

            # Session handling for the functions, that show data:
            # Also exclude custom-style.css, since the CSRF check
            # will always fail and return a HTTP 401 anyway.
            # A HTTP 404 makes more sense.
            if request.path.lower() in [
                "/manage/",
                "/manage",
                "/manage/logout",
                "/manage/audittrail",
                "/manage/policies",
                "/manage/tokenview",
                "/manage/userview",
                "/manage/help",
                "/manage/custom-style.css",
            ]:
                pass
            else:
                check_session()

        except Exception as exx:
            log.error("[__before__::%r] exception %r" % (action, exx))
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, exx, context="before")

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#30
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context['action']

        try:
            c.audit = request_context['audit']
            c.audit['client'] = get_client(request)
            check_session(request)
            audit = config.get('audit')
            request_context['Audit'] = audit

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')
示例#31
0
    def __before__(self, action, **params):
        """
        """
        try:

            c.audit = request_context['audit']
            c.audit['success'] = False

            c.audit['client'] = get_client(request)

            # Session handling
            check_session(request)

            request_context['Audit'] = audit
            checkAuthorisation(scope='reporting.access', method=action)

            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            Session.close()
            return sendError(response, exception, context='before')
示例#32
0
    def __before__(self, action, **params):
        """
        """
        try:

            c.audit = request_context['audit']
            c.audit['success'] = False

            c.audit['client'] = get_client(request)

            # Session handling
            check_session(request)

            request_context['Audit'] = audit
            checkAuthorisation(scope='reporting.access', method=action)

            return request

        except Exception as exception:
            log.exception(exception)
            Session.rollback()
            Session.close()
            return sendError(response, exception, context='before')
示例#33
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r] %r" % (action, params))

        try:
            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)

            c.version = get_version()
            c.licenseinfo = get_copyright_info()
            c.polDefs = getPolicyDefinitions()

            # Session handling for the functions, that show data:
            # Also exclude custom-style.css, since the CSRF check
            # will always fail and return a HTTP 401 anyway.
            # A HTTP 404 makes more sense.
            if request.path.lower() in ['/manage/', '/manage',
                                        '/manage/logout',
                                        '/manage/audittrail',
                                        '/manage/policies',
                                        '/manage/tokenview',
                                        '/manage/userview',
                                        '/manage/help',
                                        '/manage/custom-style.css']:
                pass
            else:
                check_session(request)

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            log.debug("[__before__::%r] done" % (action))
示例#34
0
    def __before__(self, action, **params):
        '''
        '''

        try:

            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)
            request_context['Audit'] = audit

            # Session handling
            if action not in ['getsession', 'dropsession']:
                check_session(request, scope='helpdesk')

            return request

        except Exception as exx:
            log.exception("[__before__::%r] exception", action)

            Session.rollback()
            Session.close()

            return sendError(response, exx, context='before')
示例#35
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r]" % (action))
        valid_request = False
        try:
            for key, value in params.items():
                log.debug("[__before__::%r:%r]" % (key, value))

            audit.initialize()
            c.audit['client'] = get_client()

            self.storage = config.get('openid_sql')

            getCookieExpire = int(config.get("linotpOpenID.CookieExpire", -1))

            self.COOKIE_EXPIRE = 3600
            if getCookieExpire >= 0:
                self.COOKIE_EXPIRE = getCookieExpire

            c.logged_in = False
            c.login = ""
            c.version = get_version()
            c.licenseinfo = get_copyright_info()

            http_host = request.environ.get("HTTP_HOST")
            log.debug("[__before__] Doing openid request from host %s" %
                      http_host)
            if not is_valid_fqdn(http_host, split_port=True):
                err = "Bad hostname: %s" % http_host
                audit.log(c.audit)
                c.audit["action_detail"] = err
                log.error(err)
                raise HTTPBadRequest(err)

            self.BASEURL = request.environ.get(
                "wsgi.url_scheme") + "://" + http_host

            # check if the browser is logged in
            login = request.cookies.get(COOKIE_NAME)

            if login:
                c.logged_in = True

            ## default return for the __before__ and __after__
            log.debug("[__before__::%r]" % (response))
            valid_request = True
            return response

        except PolicyException as pex:
            log.error("[__before__::%r] policy exception %r" % (action, pex))
            log.error("[__before__] %s" % traceback.format_exc())
            return sendError(response, pex, context='before')

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.error("[__before__::%r] webob.exception %r" % (action, acc))
            log.error("[__before__] %s" % traceback.format_exc())
            raise acc

        except Exception as exx:
            log.error("[__before__::%r] exception %r" % (action, exx))
            log.error("[__before__] %s" % traceback.format_exc())
            return sendError(response, exx, context='before')

        finally:
            if valid_request is False:
                self.storage.session.rollback()
                self.storage.session.close()

            log.debug("[__before__::%r] done" % (action))
示例#36
0
    def __before__(self, action):
        '''
        This is the authentication to self service
        If you want to do ANYTHING with selfservice, you need to be
        authenticated.  The _before_ is executed before any other function
        in this controller.
        '''

        try:

            param = request.params

            audit.initialize()
            c.audit['success'] = False
            c.audit['client'] = get_client(request)

            c.version = get_version()
            c.licenseinfo = get_copyright_info()

            self.request_context['Audit'] = audit

            (auth_type, auth_user) = get_auth_user(request)

            if not auth_user or auth_type not in ['repoze', 'selftest']:
                abort(401, "You are not authenticated")

            (c.user, _foo, c.realm) = auth_user.rpartition('@')
            self.authUser = User(c.user, c.realm, '')

            if auth_type == "repoze":
                # checking the session
                if (False == check_selfservice_session(request,
                                                       request.url,
                                                       request.path,
                                                       request.cookies,
                                                       request.params
                                                       )):
                    c.audit['action'] = request.path[1:]
                    c.audit['info'] = "session expired"
                    audit.log(c.audit)
                    abort(401, "No valid session")

            c.imprint = get_imprint(c.realm)

            c.tokenArray = []

            c.user = self.authUser.login
            c.realm = self.authUser.realm
            c.tokenArray = getTokenForUser(self.authUser)

            # only the defined actions should be displayed
            # - remark: the generic actions like enrollTT are allready approved
            #   to have a rendering section and included
            actions = getSelfserviceActions(self.authUser,
                                            context=self.request_context)
            c.actions = actions
            for policy in actions:
                if "=" in policy:
                    (name, val) = policy.split('=')
                    val = val.strip()
                    # try if val is a simple numeric -
                    # w.r.t. javascript evaluation
                    try:
                        nval = int(val)
                    except:
                        nval = val
                    c.__setattr__(name.strip(), nval)

            c.dynamic_actions = add_dynamic_selfservice_enrollment(config,
                                                                   c.actions)

            # we require to establish all token local defined
            # policies to be initialiezd
            additional_policies = add_dynamic_selfservice_policies(config,
                                                                   actions)
            for policy in additional_policies:
                c.__setattr__(policy, -1)

            c.otplen = -1
            c.totp_len = -1


            return response

        except webob.exc.HTTPUnauthorized as acc:
            # the exception, when an abort() is called if forwarded
            log.info("[__before__::%r] webob.exception %r" % (action, acc))
            log.info("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            raise acc

        except Exception as e:
            log.exception("[__before__] failed with error: %r" % e)
            Session.rollback()
            Session.close()
            return sendError(response, e, context='before')

        finally:
            log.debug('[__after__] done')
示例#37
0
文件: base.py 项目: choth02/LinOTP
    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
示例#38
0
    def __before__(self, action, **params):

        log.debug("[__before__::%r]" % (action))
        valid_request = False
        try:
            for key, value in params.items():
                log.debug("[__before__::%r:%r]" % (key, value))

            c.audit = request_context[audit]
            c.audit['client'] = get_client(request)
            request_context['Audit'] = audit

            self.storage = config.get('openid_sql')

            getCookieExpire = int(config.get("linotpOpenID.CookieExpire", -1))

            self.COOKIE_EXPIRE = 3600
            if getCookieExpire >= 0:
                self.COOKIE_EXPIRE = getCookieExpire

            c.logged_in = False
            c.login = ""
            c.version = get_version()
            c.licenseinfo = get_copyright_info()

            http_host = request.environ.get("HTTP_HOST")
            log.debug("[__before__] Doing openid request from host %s" % http_host)
            if not is_valid_fqdn(http_host, split_port=True):
                err = "Bad hostname: %s" % http_host
                audit.log(c.audit)
                c.audit["action_detail"] = err
                log.error(err)
                raise HTTPBadRequest(err)

            self.BASEURL = request.environ.get("wsgi.url_scheme") + "://" + http_host

            # check if the browser is logged in
            login = request.cookies.get(COOKIE_NAME)

            if login:
                c.logged_in = True

            ## default return for the __before__ and __after__
            log.debug("[__before__::%r]" % (response))
            valid_request = True

            return response

        except PolicyException as pex:
            log.exception("[__before__::%r] policy exception %r" % (action, pex))
            return sendError(response, pex, context='before')

        except webob.exc.HTTPUnauthorized as acc:
            ## the exception, when an abort() is called if forwarded
            log.exception("[__before__::%r] webob.exception %r" % (action, acc))
            raise acc

        except Exception as exx:
            log.exception("[__before__::%r] exception %r" % (action, exx))
            return sendError(response, exx, context='before')

        finally:
            if valid_request is False:
                self.storage.session.rollback()
                self.storage.session.close()

            log.debug("[__before__::%r] done" % (action))
示例#39
0
    def __before__(self, action):
        '''
        This is the authentication to self service
        If you want to do ANYTHING with selfservice, you need to be
        authenticated.  The _before_ is executed before any other function
        in this controller.
        '''

        try:

            param = request.params

            audit.initialize()
            c.audit['success'] = False
            c.audit['client'] = get_client()


            c.version = get_version()
            c.licenseinfo = get_copyright_info()
            if isSelfTest():
                log.debug("[__before__] Doing selftest!")
                uuser = getParam(param, "selftest_user", True)
                if uuser is not None:
                    (c.user, _foo, c.realm) = uuser.rpartition('@')
                else:
                    c.realm = ""
                    c.user = "******"
                    env = request.environ
                    uuser = env.get('REMOTE_USER')
                    if uuser is not None:
                        (c.user, _foo, c.realm) = uuser.rpartition('@')

                self.authUser = User(c.user, c.realm, '')
                log.debug("[__before__] authenticating as %s in realm %s!" % (c.user, c.realm))
            else:
                # Use WebAuth instead of LinOTP auth.
                identity = request.environ.get('REMOTE_USER')
                if identity is None:
					abort(401, "You are not authenticated")

                c.user = identity

                # Put their current realm as the first one we find them in.
                # Doesn't really matter since tokens are realm-independent.
                realms = getAllUserRealms(User(identity, "", ""))
                if (realms):
                    c.realm = realms[0]

                self.authUser = User(c.user, c.realm, '')

                # Check token expiry.
            	age = int(request.environ.get('WEBAUTH_TOKEN_EXPIRATION')) - time.time()

                # Set selfservice cookie
            	response.set_cookie('linotp_selfservice', 'REMOTE_USER', max_age = int(age))

                # Set userservice auth cookie
                self.client = get_client()
                authcookie = create_auth_cookie(config, identity, self.client)
                response.set_cookie('userauthcookie', authcookie, max_age=360*24)

                log.debug("[__before__] set the self.authUser to: %s, %s " % (self.authUser.login, self.authUser.realm))
                log.debug('[__before__] param for action %s: %s' % (action, param))

                # checking the session
                if (False == check_selfservice_session(request.url,
                                                       request.path,
                                                       request.cookies,
                                                       request.params)):
                    c.audit['action'] = request.path[1:]
                    c.audit['info'] = "session expired"
                    audit.log(c.audit)
                    abort(401, "No valid session")

            c.imprint = get_imprint(c.realm)

            c.tokenArray = []

            c.user = self.authUser.login
            c.realm = self.authUser.realm
            c.tokenArray = getTokenForUser(self.authUser)

            # only the defined actions should be displayed
            # - remark: the generic actions like enrollTT are allready approved
            #   to have a rendering section and included
            actions = getSelfserviceActions(self.authUser)
            c.actions = actions
            for policy in actions:
                if "=" in policy:
                    (name, val) = policy.split('=')
                    val = val.strip()
                    # try if val is a simple numeric -
                    # w.r.t. javascript evaluation
                    try:
                        nval = int(val)
                    except:
                        nval = val
                    c.__setattr__(name.strip(), nval)

            c.dynamic_actions = add_dynamic_selfservice_enrollment(config,
                                                                   c.actions)

            # we require to establish all token local defined
            # policies to be initialiezd
            additional_policies = add_dynamic_selfservice_policies(config,
                                                                   actions)
            for policy in additional_policies:
                c.__setattr__(policy, -1)

            c.otplen = -1
            c.totp_len = -1

            return response

        except webob.exc.HTTPUnauthorized as acc:
            # the exception, when an abort() is called if forwarded
            log.info("[__before__::%r] webob.exception %r" % (action, acc))
            log.info("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            raise acc

        except Exception as e:
            log.error("[__before__] failed with error: %r" % e)
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, e, context='before')

        finally:
            log.debug('[__before__] done')
示例#40
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context["action"]

        try:
            g.audit["success"] = False
            g.audit["client"] = get_client(request)

            c.version = get_version()
            c.version_ref = base64.encodebytes(c.version.encode())[:6]

            c.licenseinfo = get_copyright_info()
            c.polDefs = get_policy_definitions()

            c.display_provider = boolean(
                request_context["Config"].get("display_provider", True)
            )

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

            # 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

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

            # Session handling for the functions, that show data:
            # Also exclude custom-style.css, since the CSRF check
            # will always fail and return a HTTP 401 anyway.
            # A HTTP 404 makes more sense.
            if request.path.lower() in [
                "/manage/",
                "/manage",
                "/manage/login",
                "/manage/audittrail",
                "/manage/policies",
                "/manage/tokenview",
                "/manage/userview",
                "/manage/help",
                "/manage/custom-style.css",
            ]:
                pass
            else:
                check_session(request)

        except Exception as exx:
            log.error("[__before__::%r] exception %r", action, exx)
            db.session.rollback()
            return sendError(response, exx, context="before")

        finally:
            log.debug("[__before__::%r] done", action)
示例#41
0
    def create_context(self, request, environment):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        request_context['Config'] = linotp_config
        request_context['Policies'] = parse_policies(linotp_config)
        request_context['translate'] = translate
        request_context['CacheManager'] = environment['beaker.cache']

        initResolvers()

        request_params = {}

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

        request_context['Params'] = request_params

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

        request_context['AuthUser'] = authUser
        request_context['UserLookup'] = {}

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

        client = None
        try:
            client = get_client(request=request)
        except UnicodeDecodeError as exx:
            log.error("Failed 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("Failed to decode request parameters %r" % exx)

        request_context['defaultRealm'] = defaultRealm

        realms = None
        try:
            realms = getRealms()
        except UnicodeDecodeError as exx:
            log.error("Failed 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():
            sysconfig[key] = config.get(key, default)

        request_context['SystemConfig'] = sysconfig
示例#42
0
    def __before__(self, action):
        '''
        This is the authentication to self service. If you want to do
        ANYTHING with the selfservice, you need to be authenticated. The
        _before_ is executed before any other function in this controller.
        '''

        try:
            c.audit = request_context['audit']
            c.audit['success'] = False
            c.audit['client'] = get_client(request)

            c.version = get_version()
            c.licenseinfo = get_copyright_info()

            request_context['Audit'] = audit

            (auth_type, auth_user) = get_auth_user(request)

            if not auth_user or auth_type not in ['repoze', 'selftest']:
                abort(401, "You are not authenticated")

            (c.user, _foo, c.realm) = auth_user.rpartition('@')
            self.authUser = User(c.user, c.realm, '')

            if auth_type == "repoze":
                # checking the session only for not_form_access actions
                if action not in self.form_access_methods:
                    call_url = "selfservice/%s" % action
                    valid_session = check_selfservice_session(
                        url=call_url,
                        cookies=request.cookies,
                        params=request.params)
                    if not valid_session:
                        c.audit['action'] = request.path[1:]
                        c.audit['info'] = "session expired"
                        audit.log(c.audit)
                        abort(401, "No valid session")

            c.imprint = get_imprint(c.realm)

            c.tokenArray = []

            c.user = self.authUser.login
            c.realm = self.authUser.realm

            # only the defined actions should be displayed
            # - remark: the generic actions like enrollTT are allready approved
            #   to have a rendering section and included
            actions = getSelfserviceActions(self.authUser)
            c.actions = actions
            for policy in actions:
                if policy:
                    if "=" not in policy:
                        c.__setattr__(policy, -1)
                    else:
                        (name, val) = policy.split('=')
                        val = val.strip()
                        # try if val is a simple numeric -
                        # w.r.t. javascript evaluation
                        try:
                            nval = int(val)
                        except:
                            nval = val
                        c.__setattr__(name.strip(), nval)

            c.dynamic_actions = add_dynamic_selfservice_enrollment(
                config, c.actions)

            # we require to establish all token local defined
            # policies to be initialiezd
            additional_policies = add_dynamic_selfservice_policies(
                config, actions)
            for policy in additional_policies:
                c.__setattr__(policy, -1)

            c.otplen = -1
            c.totp_len = -1

            return response

        except webob.exc.HTTPUnauthorized as acc:
            # the exception, when an abort() is called if forwarded
            log.info("[__before__::%r] webob.exception %r" % (action, acc))
            log.info("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            raise acc

        except Exception as e:
            log.exception("[__before__] failed with error: %r" % e)
            Session.rollback()
            Session.close()
            return sendError(response, e, context='before')

        finally:
            log.debug('[__after__] done')
示例#43
0
    def __before__(self, action):
        '''
        This is the authentication to self service
        If you want to do ANYTHING with selfservice, you need to be
        authenticated.  The _before_ is executed before any other function
        in this controller.
        '''

        try:

            param = request.params

            audit.initialize()
            c.audit['success'] = False
            c.audit['client'] = get_client()

            c.version = get_version()
            c.licenseinfo = get_copyright_info()
            if isSelfTest():
                log.debug("[__before__] Doing selftest!")
                uuser = getParam(param, "selftest_user", True)
                if uuser is not None:
                    (c.user, _foo, c.realm) = uuser.rpartition('@')
                else:
                    c.realm = ""
                    c.user = "******"
                    env = request.environ
                    uuser = env.get('REMOTE_USER')
                    if uuser is not None:
                        (c.user, _foo, c.realm) = uuser.rpartition('@')

                if c.user in ['--u--']:
                    abort(401, "No valid session")

                self.authUser = User(c.user, c.realm, '')
                log.debug("[__before__] authenticating as %s in realm %s!"
                          % (c.user, c.realm))
            else:
                identity = request.environ.get('repoze.who.identity')
                if identity is None:
                    abort(401, "You are not authenticated")

                log.debug("[__before__] doing getAuthFromIdentity in action %s"
                          % action)

                user_id = request.environ.get('repoze.who.identity')\
                                         .get('repoze.who.userid')
                if type(user_id) == unicode:
                    user_id = user_id.encode(ENCODING)
                identity = user_id.decode(ENCODING)
                log.debug("[__before__] getting identity from repoze.who: %r"
                           % identity)

                (c.user, _foo, c.realm) = identity.rpartition('@')
                self.authUser = User(c.user, c.realm, '')

                log.debug("[__before__] set the self.authUser to: %s, %s "
                          % (self.authUser.login, self.authUser.realm))
                log.debug('[__before__] param for action %s: %s'
                          % (action, param))

                # checking the session
                if (False == check_selfservice_session(request.url,
                                                       request.path,
                                                       request.cookies,
                                                       request.params
                                                       )):
                    c.audit['action'] = request.path[1:]
                    c.audit['info'] = "session expired"
                    audit.log(c.audit)
                    abort(401, "No valid session")

            c.imprint = get_imprint(c.realm)

            c.tokenArray = []

            c.user = self.authUser.login
            c.realm = self.authUser.realm

            c.tokenArray = getTokenForUser(self.authUser)

            # only the defined actions should be displayed
            # - remark: the generic actions like enrollTT are allready approved
            #   to have a rendering section and included
            actions = getSelfserviceActions(self.authUser)
            c.actions = actions
            for policy in actions:
                if "=" in policy:
                    (name, val) = policy.split('=')
                    val = val.strip()
                    # try if val is a simple numeric -
                    # w.r.t. javascript evaluation
                    try:
                        nval = int(val)
                    except:
                        nval = val
                    c.__setattr__(name.strip(), nval)

            c.dynamic_actions = add_dynamic_selfservice_enrollment(config,
                                                                   c.actions)

            # we require to establish all token local defined
            # policies to be initialiezd
            additional_policies = add_dynamic_selfservice_policies(config,
                                                                   actions)
            for policy in additional_policies:
                c.__setattr__(policy, -1)

            c.otplen = -1
            c.totp_len = -1

            return response

        except webob.exc.HTTPUnauthorized as acc:
            # the exception, when an abort() is called if forwarded
            log.info("[__before__::%r] webob.exception %r" % (action, acc))
            log.info("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            raise acc

        except Exception as e:
            log.error("[__before__] failed with error: %r" % e)
            log.error("[__before__] %s" % traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, e, context='before')

        finally:
            log.debug('[__after__] done')
示例#44
0
    def create_context(self, request, environment):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        request_context['Config'] = linotp_config
        request_context['Policies'] = parse_policies(linotp_config)
        request_context['translate'] = translate
        request_context['CacheManager'] = environment['beaker.cache']
        request_context['Path'] = environment.get("PATH_INFO", "") or ""
        request_context['hsm'] = self.hsm

        request_params = {}

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

        request_context['Params'] = request_params

        initResolvers()

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

        request_context['Client'] = client

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

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

        request_context['AuthUser'] = authUser
        request_context['UserLookup'] = {}

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


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

        request_context['defaultRealm'] = defaultRealm

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

        request_context['Realms'] = realms

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

        # for the setup of encrypted data, we require the hsm is instatiated
        # and available in the request context

        if not self.secret_key:
            init_key_partition(linotp_config, partition=0)

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

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

        sysconfig = {}
        for key, default in syskeys.items():
            sysconfig[key] = config.get(key, default)

        request_context['SystemConfig'] = sysconfig
示例#45
0
    def __before__(self, action):
        '''
        This is the authentication to self service. If you want to do
        ANYTHING with the selfservice, you need to be authenticated. The
        _before_ is executed before any other function in this controller.
        '''

        self.redirect = None

        try:
            c.version = get_version()
            c.licenseinfo = get_copyright_info()

            c.audit = request_context['audit']
            c.audit['success'] = False
            self.client = get_client(request)
            c.audit['client'] = self.client

            request_context['Audit'] = audit

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

            # handle requests which dont require authetication

            if action in ['logout', 'custom_style']:
                return

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

            # get the authenticated user

            auth_type, auth_user, auth_state = get_auth_user(request)

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

            # handle not authenticated requests

            if not auth_user or auth_type not in ['user_selfservice']:

                if action in ['login']:
                    return

                if action in ['index']:
                    self.redirect = True
                    redirect(url(controller='selfservice', action='login'))

                else:
                    abort(403, "No valid session")

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

            # handle authenticated requests

            # there is only one special case, which is the login that
            # could be forwarded to the index page

            if action in ['login']:
                if auth_state != 'authenticated':
                    return

                self.redirect = True
                redirect(url(controller='selfservice', action='index'))

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

            # in case of user_selfservice, an unauthenticated request should always go to login
            if auth_user and auth_type is 'user_selfservice' \
                    and auth_state is not 'authenticated':
                self.redirect = True
                redirect(url(controller='selfservice', action='login'))

            # futher processing with the authenticated user

            if auth_state != 'authenticated':
                abort(403, "No valid session")

            c.user = auth_user.login
            c.realm = auth_user.realm
            self.authUser = auth_user

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

            # authenticated session verification

            if auth_type == 'user_selfservice':

                # checking the session only for not_form_access actions
                if action not in self.form_access_methods:

                    valid_session = check_session(request, auth_user,
                                                  self.client)

                    if not valid_session:
                        c.audit['action'] = request.path[1:]
                        c.audit['info'] = "session expired"
                        audit.log(c.audit)

                        abort(403, "No valid session")

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

            c.imprint = get_imprint(c.realm)

            c.tokenArray = []

            c.user = self.authUser.login
            c.realm = self.authUser.realm

            # only the defined actions should be displayed
            # - remark: the generic actions like enrollTT are allready approved
            #   to have a rendering section and included
            actions = getSelfserviceActions(self.authUser)
            c.actions = actions
            for policy in actions:
                if policy:
                    if "=" not in policy:
                        c.__setattr__(policy, -1)
                    else:
                        (name, val) = policy.split('=')
                        val = val.strip()
                        # try if val is a simple numeric -
                        # w.r.t. javascript evaluation
                        try:
                            nval = int(val)
                        except ValueError:
                            nval = val
                        c.__setattr__(name.strip(), nval)

            c.dynamic_actions = add_dynamic_selfservice_enrollment(
                config, c.actions)

            # we require to establish all token local defined
            # policies to be initialiezd
            additional_policies = add_dynamic_selfservice_policies(
                config, actions)
            for policy in additional_policies:
                c.__setattr__(policy, -1)

            c.otplen = -1
            c.totp_len = -1

            c.pin_policy = _get_auth_PinPolicy(user=self.authUser)

            return response

        except (webob.exc.HTTPUnauthorized, webob.exc.HTTPForbidden) as acc:
            # the exception, when an abort() is called if forwarded
            log.info("[__before__::%r] webob.exception %r" % (action, acc))
            Session.rollback()
            Session.close()
            raise acc

        except HTTPFound as exx:
            raise exx

        except Exception as e:
            log.exception("[__before__] failed with error: %r" % e)
            Session.rollback()
            Session.close()
            return sendError(response, e, context='before')
示例#46
0
    def create_context(self, request, environment):
        """
        create the request context for all controllers
        """

        linotp_config = getLinotpConfig()

        # make the request id available in the request context
        request_context['RequestId'] = environment['REQUEST_ID']

        # a request local cache to get the user info from the resolver
        request_context['UserLookup'] = {}

        # a request local cache to get the resolver from user and realm
        request_context['UserRealmLookup'] = {}

        request_context['Config'] = linotp_config
        request_context['Policies'] = parse_policies(linotp_config)
        request_context['translate'] = translate
        request_context['CacheManager'] = environment['beaker.cache']

        routes = environment.get('pylons.routes_dict', {})
        path = "/%s/%s" % (routes['controller'], routes['action'])
        request_context['Path'] = path

        request_context['hsm'] = self.hsm

        initResolvers()

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

        request_context['Client'] = client

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

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

        request_context['AuthUser'] = authUser
        request_context['UserLookup'] = {}

        # ------------------------------------------------------------------ --
        # get the current resolvers

        resolvers = []
        try:
            resolvers = getResolverList(config=linotp_config)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r" % exx)

        request_context['Resolvers'] = resolvers

        # ------------------------------------------------------------------ --
        # get the current realms

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

        request_context['Realms'] = realms

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

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

        request_context['defaultRealm'] = defaultRealm

        # ------------------------------------------------------------------ --
        # load the requesting user

        from linotp.useridresolver.UserIdResolver import (
            ResolverNotAvailable)

        requestUser = None
        try:
            requestUser = getUserFromParam(self.request_params)
        except UnicodeDecodeError as exx:
            log.error("Failed to decode request parameters %r", exx)
        except (ResolverNotAvailable, NoResolverFound) as exx:
            log.error("Failed to connect to server %r", exx)

        request_context['RequestUser'] = requestUser

        # ------------------------------------------------------------------ --
        # load the providers

        from linotp.provider import Provider_types
        from linotp.provider import getProvider

        provider = {}
        for provider_type in Provider_types.keys():
            provider[provider_type] = getProvider(provider_type)

        request_context['Provider'] = provider

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

        # for the setup of encrypted data, we require the hsm is instatiated
        # and available in the request context

        if not self.secret_key:
            init_key_partition(linotp_config, partition=0)

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

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

        sysconfig = {}
        for key, default in syskeys.items():
            sysconfig[key] = config.get(key, default)

        request_context['SystemConfig'] = sysconfig
示例#47
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
示例#48
0
    def __before__(self, **params):
        """
        __before__ is called before every action

        This is the authentication to self service. If you want to do
        ANYTHING with the selfservice, you need to be authenticated. The
        _before_ is executed before any other function in this controller.

        :param params: list of named arguments
        :return: -nothing- or in case of an error a Response
                created by sendError with the context info 'before'
        """

        action = request_context['action']
        self.redirect = None

        try:
            c.version = get_version()
            c.licenseinfo = get_copyright_info()
            c.version_ref = base64.encodebytes(c.version.encode())[:6]

            g.audit['success'] = False
            self.client = get_client(request)
            g.audit['client'] = self.client

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

            # handle requests which dont require authetication

            if action in ['logout', 'custom_style']:
                return

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

            # get the authenticated user

            auth_type, auth_user, auth_state = get_auth_user(request)

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

            # handle not authenticated requests

            if not auth_user or auth_type not in ['user_selfservice']:

                if action in ['login']:
                    return

                if action in ['index']:
                    self.redirect = True
                    return redirect(url_for('.login'))

                else:
                    raise Unauthorized('No valid session')

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

            # handle authenticated requests

            # there is only one special case, which is the login that
            # could be forwarded to the index page

            if action in ['login']:
                if auth_state != 'authenticated':
                    return

                self.redirect = True
                return redirect(url_for('.index'))

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

            # in case of user_selfservice, an unauthenticated request should always go to login
            if auth_user and auth_type == 'user_selfservice' \
                    and auth_state != 'authenticated':
                self.redirect = True
                return redirect(url_for('.login'))

            # futher processing with the authenticated user

            if auth_state != 'authenticated':
                raise Unauthorized('No valid session')

            c.user = auth_user.login
            c.realm = auth_user.realm
            self.authUser = auth_user

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

            # authenticated session verification

            if auth_type == 'user_selfservice':

                # checking the session only for not_form_access actions
                if action not in self.form_access_methods:

                    valid_session = check_session(request,
                                                  auth_user,
                                                  self.client)

                    if not valid_session:
                        g.audit['action'] = request.path[1:]
                        g.audit['info'] = "session expired"
                        current_app.audit_obj.log(g.audit)

                        raise Unauthorized('No valid session')

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

            c.imprint = get_imprint(c.realm)

            c.tokenArray = []

            c.user = self.authUser.login
            c.realm = self.authUser.realm

            # only the defined actions should be displayed
            # - remark: the generic actions like enrollTT are allready approved
            #   to have a rendering section and included
            actions = get_selfservice_actions(self.authUser)
            c.actions = actions

            for action_name, action_value in actions.items():
                if action_value is True:
                    c.__setattr__(action_name, -1)
                    continue
                c.__setattr__(action_name, action_value)

            c.dynamic_actions = add_dynamic_selfservice_enrollment(config,
                                                                   c.actions)

            # we require to establish all token local defined
            # policies to be initialiezd
            additional_policies = add_dynamic_selfservice_policies(config,
                                                                   actions)
            for policy in additional_policies:
                c.__setattr__(policy, -1)

            c.otplen = -1
            c.totp_len = -1

            c.pin_policy = _get_auth_PinPolicy(user=self.authUser)

        except (flap.HTTPUnauthorized, flap.HTTPForbidden) as acc:
            # the exception, when an abort() is called if forwarded
            log.info("[__before__::%r] webob.exception %r" % (action, acc))
            db.session.rollback()
            raise acc

        except Exception as e:
            log.exception("[__before__] failed with error: %r" % e)
            db.session.rollback()
            return sendError(response, e, context='before')