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


Python User.get_by_name方法代码示例

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


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

示例1: _get_username_for_request

# 需要导入模块: from st2common.persistence.auth import User [as 别名]
# 或者: from st2common.persistence.auth.User import get_by_name [as 别名]
    def _get_username_for_request(self, username, request):
        impersonate_user = getattr(request, 'user', None)

        if impersonate_user is not None:
            # check this is a service account
            try:
                if not User.get_by_name(username).is_service:
                    message = "Current user is not a service and cannot " \
                              "request impersonated tokens"
                    abort_request(status_code=http_client.BAD_REQUEST,
                                  message=message)
                    return
                username = impersonate_user
            except (UserNotFoundError, StackStormDBObjectNotFoundError):
                message = "Could not locate user %s" % \
                          (impersonate_user)
                abort_request(status_code=http_client.BAD_REQUEST,
                              message=message)
                return
        else:
            impersonate_user = getattr(request, 'impersonate_user', None)
            nickname_origin = getattr(request, 'nickname_origin', None)
            if impersonate_user is not None:
                try:
                    # check this is a service account
                    if not User.get_by_name(username).is_service:
                        raise NotServiceUserError()
                    username = User.get_by_nickname(impersonate_user,
                                                    nickname_origin).name
                except NotServiceUserError:
                    message = "Current user is not a service and cannot " \
                              "request impersonated tokens"
                    abort_request(status_code=http_client.BAD_REQUEST,
                                  message=message)
                    return
                except (UserNotFoundError, StackStormDBObjectNotFoundError):
                    message = "Could not locate user %[email protected]%s" % \
                              (impersonate_user, nickname_origin)
                    abort_request(status_code=http_client.BAD_REQUEST,
                                  message=message)
                    return
                except NoNicknameOriginProvidedError:
                    message = "Nickname origin is not provided for nickname '%s'" % \
                              impersonate_user
                    abort_request(status_code=http_client.BAD_REQUEST,
                                  message=message)
                    return
                except AmbiguousUserError:
                    message = "%[email protected]%s matched more than one username" % \
                              (impersonate_user, nickname_origin)
                    abort_request(status_code=http_client.BAD_REQUEST,
                                  message=message)
                    return
        return username
开发者ID:nzlosh,项目名称:st2,代码行数:56,代码来源:handlers.py

示例2: create_token

# 需要导入模块: from st2common.persistence.auth import User [as 别名]
# 或者: from st2common.persistence.auth.User import get_by_name [as 别名]
def create_token(username, ttl=None, metadata=None, add_missing_user=True, service=False):
    """
    :param username: Username of the user to create the token for. If the account for this user
                     doesn't exist yet it will be created.
    :type username: ``str``

    :param ttl: Token TTL (in seconds).
    :type ttl: ``int``

    :param metadata: Optional metadata to associate with the token.
    :type metadata: ``dict``

    :param add_missing_user: Add the user given by `username` if they don't exist
    :type  add_missing_user: ``bool``

    :param service: True if this is a service (non-user) token.
    :type service: ``bool``
    """

    if ttl:
        # Note: We allow arbitrary large TTLs for service tokens.
        if not service and ttl > cfg.CONF.auth.token_ttl:
            msg = ('TTL specified %s is greater than max allowed %s.' % (ttl,
                                                                         cfg.CONF.auth.token_ttl))
            raise TTLTooLargeException(msg)
    else:
        ttl = cfg.CONF.auth.token_ttl

    if username:
        try:
            User.get_by_name(username)
        except:
            if add_missing_user:
                user_db = UserDB(name=username)
                User.add_or_update(user_db)

                extra = {'username': username, 'user': user_db}
                LOG.audit('Registered new user "%s".' % (username), extra=extra)
            else:
                raise UserNotFoundError()

    token = uuid.uuid4().hex
    expiry = date_utils.get_datetime_utc_now() + datetime.timedelta(seconds=ttl)
    token = TokenDB(user=username, token=token, expiry=expiry, metadata=metadata, service=service)
    Token.add_or_update(token)

    username_string = username if username else 'an anonymous user'
    token_expire_string = isotime.format(expiry, offset=False)
    extra = {'username': username, 'token_expiration': token_expire_string}

    LOG.audit('Access granted to "%s" with the token set to expire at "%s".' %
              (username_string, token_expire_string), extra=extra)

    return token
开发者ID:StackStorm,项目名称:st2,代码行数:56,代码来源:access.py

示例3: post

# 需要导入模块: from st2common.persistence.auth import User [as 别名]
# 或者: from st2common.persistence.auth.User import get_by_name [as 别名]
    def post(self, api_key_api, requester_user):
        """
        Create a new entry.
        """

        permission_type = PermissionType.API_KEY_CREATE
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_api_permission(user_db=requester_user,
                                                           resource_api=api_key_api,
                                                           permission_type=permission_type)

        api_key_db = None
        api_key = None
        try:
            if not getattr(api_key_api, 'user', None):
                if requester_user:
                    api_key_api.user = requester_user.name
                else:
                    api_key_api.user = cfg.CONF.system_user.user

            try:
                User.get_by_name(api_key_api.user)
            except StackStormDBObjectNotFoundError:
                user_db = UserDB(name=api_key_api.user)
                User.add_or_update(user_db)

                extra = {'username': api_key_api.user, 'user': user_db}
                LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra)

            # If key_hash is provided use that and do not create a new key. The assumption
            # is user already has the original api-key
            if not getattr(api_key_api, 'key_hash', None):
                api_key, api_key_hash = auth_util.generate_api_key_and_hash()
                # store key_hash in DB
                api_key_api.key_hash = api_key_hash
            api_key_db = ApiKey.add_or_update(ApiKeyAPI.to_model(api_key_api))
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for api_key data=%s.', api_key_api)
            abort(http_client.BAD_REQUEST, six.text_type(e))

        extra = {'api_key_db': api_key_db}
        LOG.audit('ApiKey created. ApiKey.id=%s' % (api_key_db.id), extra=extra)

        api_key_create_response_api = ApiKeyCreateResponseAPI.from_model(api_key_db)
        # Return real api_key back to user. A one-way hash of the api_key is stored in the DB
        # only the real value only returned at create time. Also, no masking of key here since
        # the user needs to see this value atleast once.
        api_key_create_response_api.key = api_key

        return Response(json=api_key_create_response_api, status=http_client.CREATED)
开发者ID:StackStorm,项目名称:st2,代码行数:52,代码来源:auth.py

示例4: create_token

# 需要导入模块: from st2common.persistence.auth import User [as 别名]
# 或者: from st2common.persistence.auth.User import get_by_name [as 别名]
def create_token(username, ttl=None, metadata=None):
    """
    :param username: Username of the user to create the token for. If the account for this user
                     doesn't exist yet it will be created.
    :type username: ``str``

    :param ttl: Token TTL (in seconds).
    :type ttl: ``int``

    :param metadata: Optional metadata to associate with the token.
    :type metadata: ``dict``
    """

    if ttl:
        if ttl > cfg.CONF.auth.token_ttl:
            msg = 'TTL specified %s is greater than max allowed %s.' % (
                ttl, cfg.CONF.auth.token_ttl
            )
            raise TTLTooLargeException(msg)
    else:
        ttl = cfg.CONF.auth.token_ttl

    if username:
        try:
            User.get_by_name(username)
        except:
            user = UserDB(name=username)
            User.add_or_update(user)

            extra = {'username': username, 'user': user}
            LOG.audit('Registered new user "%s".' % (username), extra=extra)

    token = uuid.uuid4().hex
    expiry = datetime.datetime.utcnow() + datetime.timedelta(seconds=ttl)
    expiry = isotime.add_utc_tz(expiry)
    token = TokenDB(user=username, token=token, expiry=expiry, metadata=metadata)
    Token.add_or_update(token)

    username_string = username if username else 'an anonymous user'
    token_expire_string = isotime.format(expiry, offset=False)
    extra = {'username': username, 'token_expiration': token_expire_string}

    LOG.audit('Access granted to "%s" with the token set to expire at "%s".' %
              (username_string, token_expire_string), extra=extra)

    return token
开发者ID:Kailashkatheth1,项目名称:st2,代码行数:48,代码来源:access.py

示例5: put

# 需要导入模块: from st2common.persistence.auth import User [as 别名]
# 或者: from st2common.persistence.auth.User import get_by_name [as 别名]
    def put(self, api_key_api, api_key_id_or_key, requester_user):
        api_key_db = ApiKey.get_by_key_or_id(api_key_id_or_key)

        permission_type = PermissionType.API_KEY_MODIFY
        rbac_utils = get_rbac_backend().get_utils_class()
        rbac_utils.assert_user_has_resource_db_permission(user_db=requester_user,
                                                          resource_db=api_key_db,
                                                          permission_type=permission_type)

        old_api_key_db = api_key_db
        api_key_db = ApiKeyAPI.to_model(api_key_api)

        try:
            User.get_by_name(api_key_api.user)
        except StackStormDBObjectNotFoundError:
            user_db = UserDB(name=api_key_api.user)
            User.add_or_update(user_db)

            extra = {'username': api_key_api.user, 'user': user_db}
            LOG.audit('Registered new user "%s".' % (api_key_api.user), extra=extra)

        # Passing in key_hash as MASKED_ATTRIBUTE_VALUE is expected since we do not
        # leak it out therefore it is expected we get the same value back. Interpret
        # this special code and empty value as no-change
        if api_key_db.key_hash == MASKED_ATTRIBUTE_VALUE or not api_key_db.key_hash:
            api_key_db.key_hash = old_api_key_db.key_hash

        # Rather than silently ignore any update to key_hash it is better to explicitly
        # disallow and notify user.
        if old_api_key_db.key_hash != api_key_db.key_hash:
            raise ValueError('Update of key_hash is not allowed.')

        api_key_db.id = old_api_key_db.id
        api_key_db = ApiKey.add_or_update(api_key_db)

        extra = {'old_api_key_db': old_api_key_db, 'new_api_key_db': api_key_db}
        LOG.audit('API Key updated. ApiKey.id=%s.' % (api_key_db.id), extra=extra)
        api_key_api = ApiKeyAPI.from_model(api_key_db)

        return api_key_api
开发者ID:StackStorm,项目名称:st2,代码行数:42,代码来源:auth.py

示例6: __call__

# 需要导入模块: from st2common.persistence.auth import User [as 别名]
# 或者: from st2common.persistence.auth.User import get_by_name [as 别名]
    def __call__(self, req):
        """
        The method is invoked on every request and shows the lifecycle of the request received from
        the middleware.

        Although some middleware may use parts of the API spec, it is safe to assume that if you're
        looking for the particular spec property handler, it's most likely a part of this method.

        At the time of writing, the only property being utilized by middleware was `x-log-result`.
        """
        LOG.debug("Received call with WebOb: %s", req)
        endpoint, path_vars = self.match(req)
        LOG.debug("Parsed endpoint: %s", endpoint)
        LOG.debug("Parsed path_vars: %s", path_vars)

        context = copy.copy(getattr(self, 'mock_context', {}))
        cookie_token = None

        # Handle security
        if 'security' in endpoint:
            security = endpoint.get('security')
        else:
            security = self.spec.get('security', [])

        if self.auth and security:
            try:
                security_definitions = self.spec.get('securityDefinitions', {})
                for statement in security:
                    declaration, options = statement.copy().popitem()
                    definition = security_definitions[declaration]

                    if definition['type'] == 'apiKey':
                        if definition['in'] == 'header':
                            token = req.headers.get(definition['name'])
                        elif definition['in'] == 'query':
                            token = req.GET.get(definition['name'])
                        elif definition['in'] == 'cookie':
                            token = req.cookies.get(definition['name'])
                        else:
                            token = None

                        if token:
                            auth_func = op_resolver(definition['x-operationId'])
                            auth_resp = auth_func(token)

                            # Include information on how user authenticated inside the context
                            if 'auth-token' in definition['name'].lower():
                                auth_method = 'authentication token'
                            elif 'api-key' in definition['name'].lower():
                                auth_method = 'API key'

                            context['user'] = User.get_by_name(auth_resp.user)
                            context['auth_info'] = {
                                'method': auth_method,
                                'location': definition['in']
                            }

                            # Also include token expiration time when authenticated via auth token
                            if 'auth-token' in definition['name'].lower():
                                context['auth_info']['token_expire'] = auth_resp.expiry

                            if 'x-set-cookie' in definition:
                                max_age = auth_resp.expiry - date_utils.get_datetime_utc_now()
                                cookie_token = cookies.make_cookie(definition['x-set-cookie'],
                                                                   token,
                                                                   max_age=max_age,
                                                                   httponly=True)

                            break

                if 'user' not in context:
                    raise auth_exc.NoAuthSourceProvidedError('One of Token or API key required.')
            except (auth_exc.NoAuthSourceProvidedError,
                    auth_exc.MultipleAuthSourcesError) as e:
                LOG.error(str(e))
                return abort_unauthorized(str(e))
            except auth_exc.TokenNotProvidedError as e:
                LOG.exception('Token is not provided.')
                return abort_unauthorized(str(e))
            except auth_exc.TokenNotFoundError as e:
                LOG.exception('Token is not found.')
                return abort_unauthorized(str(e))
            except auth_exc.TokenExpiredError as e:
                LOG.exception('Token has expired.')
                return abort_unauthorized(str(e))
            except auth_exc.ApiKeyNotProvidedError as e:
                LOG.exception('API key is not provided.')
                return abort_unauthorized(str(e))
            except auth_exc.ApiKeyNotFoundError as e:
                LOG.exception('API key is not found.')
                return abort_unauthorized(str(e))
            except auth_exc.ApiKeyDisabledError as e:
                LOG.exception('API key is disabled.')
                return abort_unauthorized(str(e))

            if cfg.CONF.rbac.enable:
                user_db = context['user']

                permission_type = endpoint.get('x-permissions', None)
                if permission_type:
#.........这里部分代码省略.........
开发者ID:lyandut,项目名称:st2,代码行数:103,代码来源:router.py


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