Python itsdangerous.BadSignature() Examples

The following are 30 code examples of itsdangerous.BadSignature(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module itsdangerous , or try the search function .
Example #1
Source File: user.py    From flask-base with MIT License 7 votes vote down vote up
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 
Example #2
Source File: user.py    From penn-club-ratings with MIT License 6 votes vote down vote up
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 
Example #3
Source File: tokens.py    From walle-web with Apache License 2.0 6 votes vote down vote up
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) 
Example #4
Source File: __init__.py    From CTFd with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: session.py    From Flask-Unsign with MIT License 6 votes vote down vote up
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 
Example #6
Source File: user_handler.py    From cloudify-manager with Apache License 2.0 6 votes vote down vote up
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 
Example #7
Source File: models.py    From realms-wiki with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #8
Source File: email_links.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def on_delete_signup(token):
    """Endpoint to delete signups via email"""
    try:
        s = URLSafeSerializer(get_token_secret())
        signup_id = ObjectId(s.loads(token))
    except BadSignature:
        return "Unknown token"

    deleteitem_internal('eventsignups', concurrency_check=False,
                        **{current_app.config['ID_FIELD']: signup_id})

    redirect_url = current_app.config.get('SIGNUP_DELETED_REDIRECT')
    if redirect_url:
        return redirect(redirect_url)
    else:
        return current_app.config['SIGNUP_DELETED_TEXT'] 
Example #9
Source File: views.py    From online-ratings with MIT License 6 votes vote down vote up
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')) 
Example #10
Source File: api.py    From microblog.pub with GNU Affero General Public License v3.0 6 votes vote down vote up
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}") 
Example #11
Source File: authorization.py    From sawtooth-marketplace with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: api.py    From golem with MIT License 6 votes vote down vote up
def auth_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if not current_user.is_authenticated:
            token = request.headers.get('token', None)
            if token:
                try:
                    user = Users.verify_auth_token(current_app.secret_key, token)
                    request.api_user = user
                except SignatureExpired:
                    abort(401, 'Signature Expired')
                except BadSignature:
                    abort(401, 'Token did not match')
                except Exception:
                    abort(401, 'Unknown error')
            else:
                abort(400, 'Missing token')
        return func(*args, **kwargs)
    return decorated_view 
Example #13
Source File: users.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
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() 
Example #14
Source File: users.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
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 
Example #15
Source File: models.py    From JmilkFan-s-Blog with Apache License 2.0 6 votes vote down vote up
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 
Example #16
Source File: user.py    From BhagavadGita with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #17
Source File: sessions.py    From quart with MIT License 6 votes vote down vote up
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() 
Example #18
Source File: route_handler.py    From education-sawtooth-simple-supply with Apache License 2.0 6 votes vote down vote up
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']) 
Example #19
Source File: actor_auth_cookie.py    From datasette with Apache License 2.0 6 votes vote down vote up
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 
Example #20
Source File: user.py    From penn-club-ratings with MIT License 5 votes vote down vote up
def reset_password(self, token, new_password):
        """Verify the new password for this user."""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except (BadSignature, SignatureExpired):
            return False
        if data.get('reset') != self.id:
            return False
        self.password = new_password
        db.session.add(self)
        db.session.commit()
        return True 
Example #21
Source File: user_management_test.py    From golem with MIT License 5 votes vote down vote up
def test_verify_auth_token_invalid_token(self, testdir_class, test_utils):
        testdir_class.activate()
        username = test_utils.random_string(5)
        password = '123456'
        Users.create_user(username, password)
        app = create_app()
        with pytest.raises(BadSignature) as _:
            Users.verify_auth_token(app.secret_key, 'invalid_token') 
Example #22
Source File: sessions.py    From data with GNU General Public License v3.0 5 votes vote down vote up
def open_session(self, app, request):
        s = self.get_signing_serializer(app)
        if s is None:
            return None
        val = request.cookies.get(app.session_cookie_name)
        if not val:
            return self.session_class()
        max_age = total_seconds(app.permanent_session_lifetime)
        try:
            data = s.loads(val, max_age=max_age)
            return self.session_class(data)
        except BadSignature:
            return self.session_class() 
Example #23
Source File: user.py    From flask-base with MIT License 5 votes vote down vote up
def reset_password(self, token, new_password):
        """Verify the new password for this user."""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except (BadSignature, SignatureExpired):
            return False
        if data.get('reset') != self.id:
            return False
        self.password = new_password
        db.session.add(self)
        db.session.commit()
        return True 
Example #24
Source File: sessions.py    From cloud-playground with Apache License 2.0 5 votes vote down vote up
def open_session(self, app, request):
        s = self.get_signing_serializer(app)
        if s is None:
            return None
        val = request.cookies.get(app.session_cookie_name)
        if not val:
            return self.session_class()
        max_age = total_seconds(app.permanent_session_lifetime)
        try:
            data = s.loads(val, max_age=max_age)
            return self.session_class(data)
        except BadSignature:
            return self.session_class() 
Example #25
Source File: users.py    From nyaa with GNU General Public License v3.0 5 votes vote down vote up
def activate_user(payload):
    if app.config['MAINTENANCE_MODE']:
        flask.flash(flask.Markup('<strong>Activations are currently disabled.</strong>'), 'danger')
        return flask.redirect(flask.url_for('main.home'))

    s = get_serializer()
    try:
        user_id = s.loads(payload)
    except BadSignature:
        flask.abort(404)

    user = models.User.by_id(user_id)

    # Only allow activating inactive users
    if not user or user.status != models.UserStatusType.INACTIVE:
        flask.abort(404)

    # Set user active
    user.status = models.UserStatusType.ACTIVE
    db.session.add(user)
    db.session.commit()

    # Log user in
    flask.g.user = user
    flask.session['user_id'] = user.id
    flask.session.permanent = True
    flask.session.modified = True

    flask.flash(flask.Markup("You've successfully verified your account!"), 'success')
    return flask.redirect(flask.url_for('main.home')) 
Example #26
Source File: session.py    From conifer with Apache License 2.0 5 votes vote down vote up
def signed_cookie_to_id(self, sesh_cookie):
        serial = URLSafeTimedSerializer(self.secret_key)

        try:
            return serial.loads(sesh_cookie)
        except BadSignature as b:
            return None 
Example #27
Source File: api.py    From microblog.pub with GNU Affero General Public License v3.0 5 votes vote down vote up
def api_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        try:
            _api_required()
        except BadSignature:
            abort(401)

        return f(*args, **kwargs)

    return decorated_function 
Example #28
Source File: app.py    From microblog.pub with GNU Affero General Public License v3.0 5 votes vote down vote up
def outbox():
    if request.method == "GET":
        if not is_api_request():
            abort(404)
        _log_sig()
        # TODO(tsileo): returns the whole outbox if authenticated and look at OCAP support
        q = {
            **in_outbox(),
            "$or": [
                {
                    **by_type(ActivityType.CREATE),
                    **not_deleted(),
                    **by_visibility(ap.Visibility.PUBLIC),
                },
                {**by_type(ActivityType.ANNOUNCE), **not_undo()},
            ],
        }
        return activitypubify(
            **activitypub.build_ordered_collection(
                DB.activities,
                q=q,
                cursor=request.args.get("cursor"),
                map_func=lambda doc: activity_from_doc(doc, embed=True),
                col_name="outbox",
            )
        )

    # Handle POST request aka C2S API
    try:
        _api_required()
    except BadSignature:
        abort(401)

    data = request.get_json(force=True)
    activity = ap.parse_activity(data)
    activity_id = post_to_outbox(activity)

    return Response(status=201, headers={"Location": activity_id}) 
Example #29
Source File: auth.py    From todoism with MIT License 5 votes vote down vote up
def validate_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except (BadSignature, SignatureExpired):
        return False
    user = User.query.get(data['id'])
    if user is None:
        return False
    g.current_user = user
    return True 
Example #30
Source File: sessions.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def open_session(self, app, request):
        s = self.get_signing_serializer(app)
        if s is None:
            return None
        val = request.cookies.get(app.session_cookie_name)
        if not val:
            return self.session_class()
        max_age = total_seconds(app.permanent_session_lifetime)
        try:
            data = s.loads(val, max_age=max_age)
            return self.session_class(data)
        except BadSignature:
            return self.session_class()