Python itsdangerous.BadData() Examples

The following are 7 code examples of itsdangerous.BadData(). 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: tokenstr.py    From build-relengapi with Mozilla Public License 2.0 6 votes vote down vote up
def str_to_claims(token_str):
    try:
        claims = current_app.tokenauth_serializer.loads(token_str)
    except BadData:
        logger.warning("Got invalid signature in token %r", token_str)
        return None
    except Exception:
        logger.exception("Error processing signature in token %r", token_str)
        return None

    # convert v1 to ra2
    if claims.get('v') == 1:
        return {'iss': 'ra2', 'typ': 'prm', 'jti': 't%d' % claims['id']}

    if claims.get('iss') != TOKENAUTH_ISSUER:
        return None

    return claims 
Example #2
Source File: rest.py    From notifications-api with MIT License 5 votes vote down vote up
def validate_invitation_token(invitation_type, token):

    max_age_seconds = 60 * 60 * 24 * current_app.config['INVITATION_EXPIRATION_DAYS']

    try:
        invited_user_id = check_token(token,
                                      current_app.config['SECRET_KEY'],
                                      current_app.config['DANGEROUS_SALT'],
                                      max_age_seconds)
    except SignatureExpired:
        errors = {'invitation':
                  ['Your invitation to GOV.UK Notify has expired. '
                   'Please ask the person that invited you to send you another one']}
        raise InvalidRequest(errors, status_code=400)
    except BadData:
        errors = {'invitation': 'Something’s wrong with this link. Make sure you’ve copied the whole thing.'}
        raise InvalidRequest(errors, status_code=400)

    if invitation_type == 'service':
        invited_user = get_invited_user_by_id(invited_user_id)
        return jsonify(data=invited_user_schema.dump(invited_user).data), 200
    elif invitation_type == 'organisation':
        invited_user = dao_get_invited_organisation_user(invited_user_id)
        return jsonify(data=invited_user.serialize()), 200
    else:
        raise InvalidRequest("Unrecognised invitation type: {}".format(invitation_type)) 
Example #3
Source File: weixin_user.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def verify_weixin_state(self):
        state = self.get_weixin_state()
        try:
            serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
            return serializer.loads(state) == self.get_local_netloc()
        except BadData:
            return False 
Example #4
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def session(callback):
    cookie_name = 'session'
    serializer = URLSafeSerializer(conf['SECRET'])

    def inner(*args, **kwargs):
        data_raw = data = request.get_cookie(cookie_name)
        if data_raw:
            try:
                data = serializer.loads(data_raw)
            except (BadSignature, BadData):
                data = None

        if data:
            conf['USER'] = data['username']

        request.session = data or {}

        try:
            return callback(*args, **kwargs)
        finally:
            if request.session:
                save(request.session)
            elif not data_raw:
                pass
            else:
                response.delete_cookie(cookie_name)

    def save(session):
        cookie_opts = {
            # keep session for 3 days
            'max_age': 3600 * 24 * 3,

            # for security
            'httponly': True,
            'secure': request.headers.get('X-Forwarded-Proto') == 'https',
        }
        data = serializer.dumps(session)
        response.set_cookie(cookie_name, data, **cookie_opts)
    return inner 
Example #5
Source File: rpc_views.py    From simplecoin_multi with MIT License 5 votes vote down vote up
def check_signature():
    g.signer = TimedSerializer(current_app.config['rpc_signature'])
    try:
        g.signed = g.signer.loads(request.data)
    except BadData:
        abort(403) 
Example #6
Source File: util.py    From build-relengapi with Mozilla Public License 2.0 5 votes vote down vote up
def loads(data):
        if data[:3] != 'FK:':
            raise BadData('Not a fake token')
        else:
            return json.loads(data[3:])

# sample tokens, both a function to insert, and a JSON representation of the
# corresponding result. 
Example #7
Source File: csrf.py    From RSSNewsGAE with Apache License 2.0 4 votes vote down vote up
def validate_csrf(data, secret_key=None, time_limit=None, token_key=None):
    """Check if the given data is a valid CSRF token. This compares the given
    signed token to the one stored in the session.

    :param data: The signed CSRF token to be checked.
    :param secret_key: Used to securely sign the token. Default is
        ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
    :param time_limit: Number of seconds that the token is valid. Default is
        ``WTF_CSRF_TIME_LIMIT`` or 3600 seconds (60 minutes).
    :param token_key: Key where token is stored in session for comparision.
        Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.

    :raises ValidationError: Contains the reason that validation failed.

    .. versionchanged:: 0.14
        Raises ``ValidationError`` with a specific error message rather than
        returning ``True`` or ``False``.
    """

    secret_key = _get_config(
        secret_key, 'WTF_CSRF_SECRET_KEY', current_app.secret_key,
        message='A secret key is required to use CSRF.'
    )
    field_name = _get_config(
        token_key, 'WTF_CSRF_FIELD_NAME', 'csrf_token',
        message='A field name is required to use CSRF.'
    )
    time_limit = _get_config(
        time_limit, 'WTF_CSRF_TIME_LIMIT', 3600, required=False
    )

    if not data:
        raise ValidationError('The CSRF token is missing.')

    if field_name not in session:
        raise ValidationError('The CSRF session token is missing.')

    s = URLSafeTimedSerializer(secret_key, salt='wtf-csrf-token')

    try:
        token = s.loads(data, max_age=time_limit)
    except SignatureExpired:
        raise ValidationError('The CSRF token has expired.')
    except BadData:
        raise ValidationError('The CSRF token is invalid.')

    if not safe_str_cmp(session[field_name], token):
        raise ValidationError('The CSRF tokens do not match.')