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


Python itsdangerous.BadSignature方法代码示例

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


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

示例1: open_session

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def open_session(
        self, app: "Quart", request: BaseRequestWebsocket
    ) -> Optional[SecureCookieSession]:
        """Open a secure cookie based session.

        This will return None if a signing serializer is not available,
        usually if the config SECRET_KEY is not set.
        """
        signer = self.get_signing_serializer(app)
        if signer is None:
            return None

        cookie = request.cookies.get(app.session_cookie_name)
        if cookie is None:
            return self.session_class()
        try:
            data = signer.loads(cookie, max_age=app.permanent_session_lifetime.total_seconds())
            return self.session_class(**data)
        except BadSignature:
            return self.session_class() 
开发者ID:pgjones,项目名称:quart,代码行数:22,代码来源:sessions.py

示例2: actor_from_request

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def actor_from_request(datasette, request):
    if "ds_actor" not in request.cookies:
        return None
    try:
        decoded = datasette.unsign(request.cookies["ds_actor"], "actor")
        # If it has "e" and "a" keys process the "e" expiry
        if not isinstance(decoded, dict) or "a" not in decoded:
            return None
        expires_at = decoded.get("e")
        if expires_at:
            timestamp = int(baseconv.base62.decode(expires_at))
            if time.time() > timestamp:
                return None
        return decoded["a"]
    except BadSignature:
        return None 
开发者ID:simonw,项目名称:datasette,代码行数:18,代码来源:actor_auth_cookie.py

示例3: reset_password

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def reset_password(token, password):
    try:
        user_info = get_serializer().loads(token, max_age=reset_password_timeout.total_seconds())
    except BadSignature:
        raise AuthenticationError("Invalid token or token expired")

    if user_info.pop('action') != 'reset':
        raise AuthenticationError("Invalid token for password resets")

    user = User.objects(**user_info).first()
    if user is None:
        raise AuthenticationError("User not found")

    user.set_password(password)
    user.save()
    return user 
开发者ID:mitre,项目名称:cascade-server,代码行数:18,代码来源:users.py

示例4: validate_token

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def validate_token(token, timeout=default_timeout):
    """
    :param token: the URL Safe token, generated via User.generate_token
    :param datetime.timedelta timeout: The expiration time from the token
    :rtype: User
    """
    # If an exception happens, this must be handled by the caller
    try:
        user_info = get_serializer().loads(token)
    except BadSignature:
        raise AuthenticationError("Invalid token")

    # Persistent last indefinitely
    persistent = user_info.pop('persistent')
    if not persistent:
        user_info = get_serializer().loads(token, max_age=timeout.total_seconds())
        user_info.pop('persistent')

    # Don't fetch to mongo if not necessary
    user = User.objects(**user_info).first()
    if user is None:
        raise AuthenticationError("User not found")
    return user.login() 
开发者ID:mitre,项目名称:cascade-server,代码行数:25,代码来源:users.py

示例5: verify_player

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def verify_player(payload):
    s = get_serializer()
    try:
        user_id, aga_id = s.loads(payload)
    except BadSignature:
        current_app.logger.info('Verify called with invalid paylod')
        abort(404)

    if user_id != current_user.id:
        current_app.logger.warn("Verify called for id %s, but wrong user answered, %s" % (user_id, current_user))
        abort(404)

    aga_info = get_aga_info(aga_id)
    if aga_info is None:
        current_app.logger.warn("Could not fetch AGA info for aga_id %s" % aga_id)
        abort(404)
    name = aga_info.get('full_name', '')

    update_user_info(user_id, aga_id, name)
    msg = 'Linked account with AGA #%s' % aga_id
    current_app.logger.info(msg)
    return redirect(url_for('ratings.myaccount')) 
开发者ID:usgo,项目名称:online-ratings,代码行数:24,代码来源:views.py

示例6: get_token_status

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def get_token_status(token):
    """Mimic flask_security.utils.get_token_status with some changes

    :param token: The token to decrypt
    :return: A tuple: (expired, invalid, user, data)
    """
    security = current_app.extensions['security']
    serializer = security.remember_token_serializer
    max_age = security.token_max_age

    user, data, error = None, None, None
    expired, invalid = False, False

    try:
        data = serializer.loads(token, max_age=max_age)
    except SignatureExpired:
        expired = True
    except (BadSignature, TypeError, ValueError) as e:
        invalid = True
        error = e

    if data:
        user = user_datastore.find_user(id=data[0])

    return expired, invalid, user, data, error 
开发者ID:cloudify-cosmo,项目名称:cloudify-manager,代码行数:27,代码来源:user_handler.py

示例7: verify_token

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def verify_token(self, token, expiration_in_seconds):
        """ Verify token and return (is_valid, has_expired, id).
            Returns (True, False, id) on success.
            Returns (False, True, None) on expired tokens.
            Returns (False, False, None) on invalid tokens."""
        try:
            data = self.signer.unsign(token, max_age=expiration_in_seconds)
            is_valid = True
            has_expired = False
            id = self.decrypt_id(data)
        except SignatureExpired:
            is_valid = False
            has_expired = True
            id = None
        except BadSignature:
            is_valid = False
            has_expired = False
            id = None
        return (is_valid, has_expired, id) 
开发者ID:meolu,项目名称:walle-web,代码行数:21,代码来源:tokens.py

示例8: verify

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def verify(value: str, secret: str, legacy: bool=False, salt: str=DEFAULT_SALT) -> bool:
    """
    Verifies if a given value matches the signed signature
    :param value: Session cookie string to verify
    :param secret: Secret key
    :param salt: Salt (default: 'cookie-session')
    :param legacy: Should the legacy timestamp generator be used?
    :return: True if the secret key is valid
    """
    if not isinstance(secret, (bytes, str)):
        raise FlaskUnsignException(
            f"Secret must be a string-type (bytes, str) and received "
            f"{type(secret).__name__!r}. To fix this, either add quotes to the "
            f"secret {secret!r} or use the --no-literal-eval argument.")

    try:
        get_serializer(secret, legacy, salt).loads(value)
    except BadSignature:
        return False

    return True 
开发者ID:Paradoxis,项目名称:Flask-Unsign,代码行数:23,代码来源:session.py

示例9: load_token

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def load_token(token):
    # Load unsafe because payload is needed for sig
    sig_okay, payload = URLSafeSerializer(current_app.config['SECRET_KEY']).loads_unsafe(token)

    if not payload:
        return None

    # User key *could* be stored in payload to avoid user lookup in db
    user = User.get_by_id(payload.get('id'))

    if not user:
        return None

    try:
        if BaseUser.signer(sha256(user.password).hexdigest()).loads(token):
            return user
        else:
            return None
    except BadSignature:
        return None 
开发者ID:scragg0x,项目名称:realms-wiki,代码行数:22,代码来源:models.py

示例10: authorized

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def authorized():
    """Verifies that the token is valid and belongs to an existing user"""
    def decorator(func):
        @wraps(func)
        async def decorated_function(request, *args, **kwargs):
            if request.token is None:
                raise ApiUnauthorized("No bearer token provided")
            try:
                email = common.deserialize_auth_token(
                    request.app.config.SECRET_KEY,
                    request.token).get('email')
                auth_info = await auth_query.fetch_info_by_email(
                    request.app.config.DB_CONN, email)
                if auth_info is None:
                    raise ApiUnauthorized(
                        "Token does not belong to an existing user")
            except BadSignature:
                raise ApiUnauthorized("Invalid bearer token")
            response = await func(request, *args, **kwargs)
            return response
        return decorated_function
    return decorator 
开发者ID:hyperledger,项目名称:sawtooth-marketplace,代码行数:24,代码来源:authorization.py

示例11: change_email

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def change_email(self, token):
        """Verify the new email for this user."""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except (BadSignature, SignatureExpired):
            return False
        if data.get('change_email') != self.id:
            return False
        new_email = data.get('new_email')
        if new_email is None:
            return False
        if self.query.filter_by(email=new_email).first() is not None:
            return False
        self.email = new_email
        db.session.add(self)
        db.session.commit()
        return True 
开发者ID:gita,项目名称:BhagavadGita,代码行数:20,代码来源:user.py

示例12: _authorize

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def _authorize(self, request):
        token = request.headers.get('AUTHORIZATION')
        if token is None:
            raise ApiUnauthorized('No auth token provided')
        token_prefixes = ('Bearer', 'Token')
        for prefix in token_prefixes:
            if prefix in token:
                token = token.partition(prefix)[2].strip()
        try:
            token_dict = deserialize_auth_token(request.app['secret_key'],
                                                token)
        except BadSignature:
            raise ApiUnauthorized('Invalid auth token')
        public_key = token_dict.get('public_key')

        auth_resource = await self._database.fetch_auth_resource(public_key)
        if auth_resource is None:
            raise ApiUnauthorized('Token is not associated with an agent')
        return decrypt_private_key(request.app['aes_key'],
                                   public_key,
                                   auth_resource['encrypted_private_key']) 
开发者ID:hyperledger,项目名称:education-sawtooth-simple-supply,代码行数:23,代码来源:route_handler.py

示例13: verify_auth_token

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def verify_auth_token(token):
        """Validate the token whether is night."""

        serializer = Serializer(
            current_app.config['SECRET_KEY'])
        try:
            # serializer object already has tokens in itself and wait for
            # compare with token from HTTP Request /api/posts Method `POST`.
            data = serializer.loads(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None

        user = User.query.filter_by(id=data['id']).first()
        return user 
开发者ID:JmilkFan,项目名称:JmilkFan-s-Blog,代码行数:18,代码来源:models.py

示例14: _api_required

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def _api_required() -> None:
    if session.get("logged_in"):
        if request.method not in ["GET", "HEAD"]:
            # If a standard API request is made with a "login session", it must havw a CSRF token
            csrf.protect()
        return

    # Token verification
    token = request.headers.get("Authorization", "").replace("Bearer ", "")
    if not token:
        # IndieAuth token
        token = request.form.get("access_token", "")

    # Will raise a BadSignature on bad auth
    payload = JWT.loads(token)
    flask.g.jwt_payload = payload
    app.logger.info(f"api call by {payload}") 
开发者ID:tsileo,项目名称:microblog.pub,代码行数:19,代码来源:api.py

示例15: open_session

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import BadSignature [as 别名]
def open_session(self, app, request):
        sid = request.cookies.get(app.session_cookie_name)
        if not sid:
            sid = self._generate_sid()
            return self.session_class(sid=sid, permanent=self.permanent)

        if self.use_signer:
            try:
                sid_as_bytes = unsign(sid)
                sid = sid_as_bytes.decode()
            except BadSignature:
                sid = self._generate_sid()
                return self.session_class(sid=sid, permanent=self.permanent)

        if isinstance(sid, text_type) is False:
            sid = sid.decode("utf-8", "strict")
        val = cache.get(self.key_prefix + sid)
        if val is not None:
            try:
                data = self.serializer.loads(val)
                return self.session_class(data, sid=sid)
            except Exception:
                return self.session_class(sid=sid, permanent=self.permanent)
        return self.session_class(sid=sid, permanent=self.permanent) 
开发者ID:CTFd,项目名称:CTFd,代码行数:26,代码来源:__init__.py


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