当前位置: 首页>>代码示例>>Python>>正文


Python PolicyClass.checkPolicyPre方法代码示例

本文整理汇总了Python中privacyidea.lib.policy.PolicyClass.checkPolicyPre方法的典型用法代码示例。如果您正苦于以下问题:Python PolicyClass.checkPolicyPre方法的具体用法?Python PolicyClass.checkPolicyPre怎么用?Python PolicyClass.checkPolicyPre使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在privacyidea.lib.policy.PolicyClass的用法示例。


在下文中一共展示了PolicyClass.checkPolicyPre方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: MachineController

# 需要导入模块: from privacyidea.lib.policy import PolicyClass [as 别名]
# 或者: from privacyidea.lib.policy.PolicyClass import checkPolicyPre [as 别名]
class MachineController(BaseController):

    @log_with(log)
    def __before__(self, action, **params):
        '''
        '''
        try:
            c.audit['success'] = False
            c.audit['client'] = get_client()
            self.Policy = PolicyClass(request, config, c,
                                      get_privacyIDEA_config(),
                                      tokenrealms=request.params.get('serial'),
                                      token_type_list=get_token_type_list())
            self.set_language()

            self.before_identity_check(action)

            Session.commit()
            return request

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

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

        finally:
            pass

    @log_with(log)
    def __after__(self, action, **params):
        '''
        '''
        params = {}

        try:
            params.update(request.params)
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            if 'serial' in params:
                    c.audit['serial'] = request.params['serial']
                    c.audit['token_type'] = getTokenType(params.get('serial'))

            self.audit.log(c.audit)

            Session.commit()
            return request

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

        finally:
            Session.close()

    @log_with(log)
    def create(self, action, **params):
        '''
        Create a new client machine entry

        :param name: the unique name of the machine (required). Can be the FQDN.
        :param desc: description of the machine
        :param ip: The IP address of the machine
        :param decommission: A date when the machine will not be valid anymore

        :return: True or False if the creation was successful.
        '''
        try:
            res = False
            param = {}
            # check machine authorization
            self.Policy.checkPolicyPre('machine', 'create')

            param.update(request.params)
            machine_name = getParam(param, "name", required)
            ip = getParam(param, "ip", optional)
            desc = getParam(param, "desc", optional)
            decommission = getParam(param, "decommission", optional)
            machine = create_machine(machine_name, 
                                     ip=ip, 
                                     desc=desc, 
                                     decommission=decommission)
            if machine:
                res = True 
            Session.commit()
            c.audit["success"] = True
            return sendResult(response, res, 1)

        except PolicyException as pe:
            log.error("policy failed: %r" % pe)
#.........这里部分代码省略.........
开发者ID:asifiqbal,项目名称:privacyidea,代码行数:103,代码来源:machine.py

示例2: search

# 需要导入模块: from privacyidea.lib.policy import PolicyClass [as 别名]
# 或者: from privacyidea.lib.policy.PolicyClass import checkPolicyPre [as 别名]
    def search(self, action, **params):

        '''
        This functions searches within the audit trail
        It returns the audit information for the given search pattern

        method:
            audit/search

        arguments:
            key, value pairs as search patterns.

            * outform - optional: if set to "csv", than the token list will be
                        given in CSV


            or: Usually the key=values will be locally AND concatenated.
                it a parameter or=true is passed, the filters will
                be OR concatenated.

            The Flexigrid provides us the following parameters:
                ('page', u'1'), ('rp', u'100'),
                ('sortname', u'number'),
                ('sortorder', u'asc'),
                ('query', u''), ('qtype', u'serial')]
        returns:
            JSON response or csv format
        '''

        param = {}
        try:
            param.update(request.params)

            output_format = getParam(param, "outform", optional)
            Policy = PolicyClass(request, config, c,
                                 get_privacyIDEA_config(),
                                 token_type_list=get_token_type_list())
            Policy.checkPolicyPre('audit', 'view', {})

            # remove the param outform (and other parameters that should not
            # be used for search!
            search_params = {}
            for p in param:
                if p not in ["outform"]:
                    search_params[p] = param[p]

            log.debug("search params %r" % search_params)

            audit_iter = None

            if output_format == "csv":
                filename = "privacyidea-audit.csv"
                response.content_type = "application/force-download"
                response.headers['Content-'
                                 'disposition'] = ('attachment; filename=%s'
                                                   % filename)
                audit_iter = CSVAuditIterator(search_params)
            else:
                response.content_type = 'application/json'
                audit_iter = JSONAuditIterator(search_params)

            c.audit['success'] = True
            Session.commit()
            return audit_iter

        except PolicyException as pe:
            log.error("gettoken/getotp policy failed: %r" % pe)
            log.error(traceback.format_exc())
            Session.rollback()
            return sendError(response, unicode(pe), 1)

        except Exception as e:
            log.error("audit/search failed: %r" % e)
            log.error(traceback.format_exc())
            Session.rollback()
            return sendError(response,
                             "audit/search failed: %s" % unicode(e), 0)

        finally:
            Session.close()
开发者ID:cyclefusion,项目名称:privacyidea,代码行数:82,代码来源:audit.py

示例3: SystemController

# 需要导入模块: from privacyidea.lib.policy import PolicyClass [as 别名]
# 或者: from privacyidea.lib.policy.PolicyClass import checkPolicyPre [as 别名]
class SystemController(BaseController):

    '''
    The privacyidea.controllers are the implementation of the web-API to talk to the privacyIDEA server.
    The SystemController is used to configure the privacyIDEA server.
    The functions of the SystemController are invoked like this

        https://server/system/<functionname>

    The functions are described below in more detail.
    '''

    @log_with(log)
    def __before__(self, action, **params):
        '''
        __before__ is called before every action
             so we can check the authorization (fixed?)

        :param action: name of the to be called action
        :param params: the list of http parameters

        :return: return response
        :rtype:  pylon response
        '''
        try:
            c.audit['success'] = False
            c.audit['client'] = get_client()
            self.Policy = PolicyClass(request, config, c,
                                      get_privacyIDEA_config(),
                                      token_type_list = get_token_type_list())
            self.before_identity_check(action)
            
            # check authorization
            if action not in ["_add_dynamic_tokens", 'setupSecurityModule',]:
                self.Policy.checkPolicyPre('system', action)

            ## default return for the __before__ and __after__
            return response

        except PolicyException as pex:
            log.error("%r: policy exception %r" % (action, pex))
            log.error(traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, pex, context='before')

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

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

        finally:
            pass


    @log_with(log)
    def __after__(self, action, **params):
        '''
        __after is called after every action

        :return: return the response
        :rtype:  pylons response
        '''
        try:
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            self.audit.log(c.audit)
            ## default return for the __before__ and __after__
            return response

        except Exception as exx:
            log.error("exception %r" % (exx))
            log.error(traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='after')

        finally:
            pass


########################################################

    def setDefault(self):
        """
        method:
            system/set

        description:
            define default settings for tokens. These default settings
            are used when new tokens are generated. The default settings will
#.........这里部分代码省略.........
开发者ID:itd,项目名称:privacyidea,代码行数:103,代码来源:system.py

示例4: OcraController

# 需要导入模块: from privacyidea.lib.policy import PolicyClass [as 别名]
# 或者: from privacyidea.lib.policy.PolicyClass import checkPolicyPre [as 别名]

#.........这里部分代码省略.........

                        {
                            "version": "privacyIDEA 2.4",
                            "jsonrpc": "2.0",
                            "result": {
                                "status": true,
                                "value": false,
                            },
                            "detail": {
                                    "transactionid" : TRANSAKTIONSID,
                                    "data" : DATAOBJECT,
                            }
                        }

            * transactionid:
                    This is the transaction ID, that is used later for
                    verifying the Return code /TAN.

            * data:
                    This is an object (URL) which can be used to generate a
                    QR-Coide to be displayed to the QRTAN App


        exception:

        """
        res = {}
        description = 'ocra/request: request a challenge for a given user or token (serial). You must either provide a parameter "user" or a parameter "serial".'
        dataobj = ""

        try:
            param = getLowerParams(request.params)

            self.Policy.checkPolicyPre('ocra', "request")

            serial = getParam(param, 'serial', optional)
            user = getUserFromParam(param, optional)

            if user.isEmpty() and serial is None:
                ## raise exception
                log.error("user or serial is required")
                raise ParameterError("Usage: %s" % description, id=77)

            message = getParam(param, 'data'  , optional)
            if message is None:
                message = ''

            ## ocra token
            tokens = getTokens4UserOrSerial(user, serial)

            if len(tokens) > 1 :
                error = ('More than one token found: unable to create challenge '
                        'for (u:%r,s:%r)!' % (user, serial))
                log.error(error)
                raise Exception(error)

            if len(tokens) == 0:
                error = ('No token found: unable to create challenge for'
                          ' (u:%r,s:%r)!' % (user, serial))
                log.error(error)
                raise Exception(error)

            ocra = tokens[0]
            (transId, challenge, res, url) = ocra.challenge(message)

            u = urlencode({'u':str(url.encode("utf-8"))})
开发者ID:asifiqbal,项目名称:privacyidea,代码行数:70,代码来源:ocra.py

示例5: GettokenController

# 需要导入模块: from privacyidea.lib.policy import PolicyClass [as 别名]
# 或者: from privacyidea.lib.policy.PolicyClass import checkPolicyPre [as 别名]
class GettokenController(BaseController):

    '''
    The privacyidea.controllers are the implementation of the web-API to talk to the privacyIDEA server.
    The ValidateController is used to validate the username with its given OTP value.

    The Tagespasswort Token uses this controller to retrieve the current OTP value of
    the Token and be able to set it in the application
    The functions of the GettokenController are invoked like this

        https://server/gettoken/<functionname>

    The functions are described below in more detail.
    '''
    @log_with(log)
    def __before__(self, action, **params):
        try:
            c.audit['client'] = get_client()
            if request.params.get('serial'):
                tokentype = getTokenType(request.params.get('serial'))
            else:
                tokentype = None
            self.Policy = PolicyClass(request, config, c,
                                      get_privacyIDEA_config(),
                                      tokentype = tokentype,
                                      token_type_list = get_token_type_list())
            self.before_identity_check(action)


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

        finally:
            pass

    @log_with(log)
    def __after__(self, action, **params):
        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'])
        self.audit.log(c.audit)
        

    @log_with(log)
    def getmultiotp(self, action, **params):
        '''
        This function is used to retrieve multiple otp values for a given user or a given serial
        If the user has more than one token, the list of the tokens is returend.

        method:
            gettoken/getmultiotp

        
        :param serial: the serial number of the token
        :param count: number of otp values to return
        :param curTime: used ONLY for internal testing: datetime.datetime object
        :type curTime: datetime object
        :param timestamp: the unix time
        :type timestamp: int
        
        :return: JSON response
        '''

        getotp_active = config.get("privacyideaGetotp.active")
        if "True" != getotp_active:
            return sendError(response, "getotp is not activated.", 0)

        param = request.params
        ret = {}

        try:
            serial = getParam(param, "serial", required)
            tokenrealms = getTokenRealms(serial)
            count = int(getParam(param, "count", required))
            curTime = getParam(param, "curTime", optional)
            timestamp = getParam(param, "timestamp", optional)
            view = getParam(param, "view", optional)

            r1 = self.Policy.checkPolicyPre('admin', 'getotp', param,
                                            tokenrealms = tokenrealms)
            log.debug("admin-getotp returned %s" % r1)

            max_count = self.Policy.checkPolicyPre('gettoken', 'max_count', param,
                                                   tokenrealms = tokenrealms)
            log.debug("checkpolicypre returned %s" % max_count)
            if count > max_count:
                count = max_count

            log.debug("retrieving OTP value for token %s" % serial)
            ret = get_multi_otp(serial, count=int(count), curTime=curTime, timestamp=timestamp)
            ret["serial"] = serial

            c.audit['success'] = True
            Session.commit()

#.........这里部分代码省略.........
开发者ID:asifiqbal,项目名称:privacyidea,代码行数:103,代码来源:gettoken.py

示例6: MachineController

# 需要导入模块: from privacyidea.lib.policy import PolicyClass [as 别名]
# 或者: from privacyidea.lib.policy.PolicyClass import checkPolicyPre [as 别名]
class MachineController(BaseController):

    @log_with(log)
    def __before__(self, action, **params):
        '''
        '''
        try:
            c.audit['success'] = False
            c.audit['client'] = get_client()
            self.Policy = PolicyClass(request, config, c,
                                      get_privacyIDEA_config(),
                                      tokenrealms=request.params.get('serial'),
                                      token_type_list=get_token_type_list())
            self.set_language()

            self.before_identity_check(action)

            Session.commit()
            return request

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

        except Exception as exx:  # pragma: no cover
            log.error("exception %r" % (action, exx))
            log.error(traceback.format_exc())
            Session.rollback()
            Session.close()
            return sendError(response, exx, context='before')

        finally:
            pass

    @log_with(log)
    def __after__(self, action, **params):
        '''
        '''
        params = {}

        try:
            params.update(request.params)
            c.audit['administrator'] = getUserFromRequest(request).get("login")
            if 'serial' in params:
                    c.audit['serial'] = request.params['serial']
                    c.audit['token_type'] = getTokenType(params.get('serial'))

            self.audit.log(c.audit)

            Session.commit()
            return request

        except Exception as e:  # pragma: no cover
            log.error("unable to create a session cookie: %r" % e)
            log.error(traceback.format_exc())
            Session.rollback()
            return sendError(response, e, context='after')

        finally:
            Session.close()

    @log_with(log)
    def create(self, action, **params):
        '''
        Create a new client machine entry

        :param name: the unique name of the machine (required).
                     Can be the FQDN.
        :param desc: description of the machine
        :param ip: The IP address of the machine (required)
        :param decommission: A date when the machine will not be valid anymore

        :return: True or False if the creation was successful.
        '''
        try:
            res = False
            param = {}
            # check machine authorization
            self.Policy.checkPolicyPre('machine', 'create')

            param.update(request.params)
            machine_name = getParam(param, "name", required)
            ip = getParam(param, "ip", required)
            desc = getParam(param, "desc", optional)
            decommission = getParam(param, "decommission", optional)
            machine = create_machine(machine_name,
                                     ip=ip,
                                     desc=desc,
                                     decommission=decommission)
            if machine:
                res = True
            Session.commit()
            c.audit["success"] = True
            return sendResult(response, res, 1)

        except PolicyException as pe:
#.........这里部分代码省略.........
开发者ID:cyclefusion,项目名称:privacyidea,代码行数:103,代码来源:machine.py

示例7: ManageController

# 需要导入模块: from privacyidea.lib.policy import PolicyClass [as 别名]
# 或者: from privacyidea.lib.policy.PolicyClass import checkPolicyPre [as 别名]

#.........这里部分代码省略.........
        '''
        This function is used to fill the flexigrid.
        Unlike the complex /admin/show function, it only returns a
        simple array of the tokens.
        '''
        param = request.params

        try:
            #serial  = getParam(param,"serial",optional)
            c.page = getParam(param, "page", optional)
            c.filter = getParam(param, "query", optional)
            c.qtype = getParam(param, "qtype", optional)
            c.sort = getParam(param, "sortname", optional)
            c.dir = getParam(param, "sortorder", optional)
            c.psize = getParam(param, "rp", optional)

            filter_all = None
            filter_realm = None
            user = User()

            if c.qtype == "loginname":
                if "@" in c.filter:
                    (login, realm) = c.filter.split("@")
                    user = User(login, realm)
                else:
                    user = User(c.filter)

            elif c.qtype == "all":
                filter_all = c.filter
            elif c.qtype == "realm":
                filter_realm = c.filter

            # check admin authorization
            res = self.Policy.checkPolicyPre('admin', 'show', param , user=user)

            filterRealm = res['realms']
            # check if policies are active at all
            # If they are not active, we are allowed to SHOW any tokens.
            pol = self.Policy.getAdminPolicies("show")
            # If there are no admin policies, we are allowed to see all realms
            if not pol['active']:
                filterRealm = ["*"]

            # check if we only want to see ONE realm or see all realms we are allowerd to see.
            if filter_realm:
                if filter_realm in filterRealm or '*' in filterRealm:
                    filterRealm = [filter_realm]

            log.debug("admin >%s< may display the following realms: %s" % (pol['admin'], pol['realms']))
            log.debug("page: %s, filter: %s, sort: %s, dir: %s" % (c.page, c.filter, c.sort, c.dir))

            if c.page is None:
                c.page = 1
            if c.psize is None:
                c.psize = 20

            log.debug("calling TokenIterator for user=%[email protected]%s, filter=%s, filterRealm=%s"
                        % (user.login, user.realm, filter_all, filterRealm))
            c.tokenArray = TokenIterator(user, None, c.page , c.psize, filter_all, c.sort, c.dir, filterRealm=filterRealm)
            c.resultset = c.tokenArray.getResultSetInfo()
            # If we have chosen a page to big!
            lines = []
            for tok in c.tokenArray:
                lines.append(
                    { 'id' : tok['privacyIDEA.TokenSerialnumber'],
                        'cell': [
开发者ID:asifiqbal,项目名称:privacyidea,代码行数:70,代码来源:manage.py


注:本文中的privacyidea.lib.policy.PolicyClass.checkPolicyPre方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。