Python itsdangerous.SignatureExpired() Examples

The following are 30 code examples of itsdangerous.SignatureExpired(). 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: 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 #3
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 #4
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 #5
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 #6
Source File: two_factor.py    From notifications-admin with MIT License 6 votes vote down vote up
def two_factor_email(token):
    if current_user.is_authenticated:
        return redirect_when_logged_in(platform_admin=current_user.platform_admin)

    # checks url is valid, and hasn't timed out
    try:
        token_data = json.loads(check_token(
            token,
            current_app.config['SECRET_KEY'],
            current_app.config['DANGEROUS_SALT'],
            current_app.config['EMAIL_2FA_EXPIRY_SECONDS']
        ))
    except SignatureExpired:
        return render_template('views/email-link-invalid.html')

    user_id = token_data['user_id']
    # checks if code was already used
    logged_in, msg = user_api_client.check_verify_code(user_id, token_data['secret_code'], "email")

    if not logged_in:
        return render_template('views/email-link-invalid.html')
    return log_in_user(user_id) 
Example #7
Source File: verify.py    From notifications-admin with MIT License 6 votes vote down vote up
def verify_email(token):
    try:
        token_data = check_token(
            token,
            current_app.config['SECRET_KEY'],
            current_app.config['DANGEROUS_SALT'],
            current_app.config['EMAIL_EXPIRY_SECONDS']
        )
    except SignatureExpired:
        flash("The link in the email we sent you has expired. We've sent you a new one.")
        return redirect(url_for('main.resend_email_verification'))

    # token contains json blob of format: {'user_id': '...', 'secret_code': '...'} (secret_code is unused)
    token_data = json.loads(token_data)
    user = User.from_id(token_data['user_id'])
    if not user:
        abort(404)

    if user.is_active:
        flash("That verification link has expired.")
        return redirect(url_for('main.sign_in'))

    session['user_details'] = {"email": user.email_address, "id": user.id}
    user.send_verify_code()
    return redirect(url_for('main.verify')) 
Example #8
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 #9
Source File: views.py    From ecommerce_website_development with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get(self, request, token):
        """激活"""
        # print('---active---')
        serializer = Serializer(settings.SECRET_KEY, 3600 * 7)
        try:
            # 解密
            info = serializer.loads(token)
            # 获取待激活用户id
            user_id = info['confirm']
            # 激活用户
            user = User.objects.get(id=user_id)
            user.is_active = 1
            user.save()

            # 跳转登录页面
            return redirect(reverse('user:login'))
        except SignatureExpired as e:
            # 激活链接已失效
            # 实际开发: 返回页面,让你点击链接再发激活邮件
            return HttpResponse('激活链接已失效')


# /user/login 
Example #10
Source File: views.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
def password_reset(token):
    try:
        user_id = validate_password_reset_token(token)
    except BadTimeSignature:
        flash('Invalid token', 'danger')
        return redirect('/login')
    except SignatureExpired:
        flash('Expired token', 'danger')
        return redirect('/login')

    if request.method == 'POST':
        password = request.form.get('password', '')
        confirm = request.form.get('password_confirmation', '')

        if valid_new_password(password, confirm):
            user = User(get_or_404(User.get_collection(), _id=user_id))
            change_password(user, password)
            flash('Password was successfully changed.', 'success')
            return redirect('/login')

    return render_template('password_reset.html') 
Example #11
Source File: asm.py    From assembly with MIT License 6 votes vote down vote up
def unsign_data(token,  **kw):
    """
    To unsign url safe data.
    If expires_in is provided it will Time the signature
    :param token:
    :param secret_key:
    :param salt: (string) a namespace key
    :param kw:
    :return:
    """
    if len(token.split(".")) == 3:
        s = URLSafeTimedSerializer2(secret_key=__CRYPT.get("secret_key"), salt=__CRYPT.get("salt"), **kw)
        value, timestamp = s.loads(token, max_age=None, return_timestamp=True)
        now = datetime.datetime.utcnow()
        if timestamp > now:
            return value
        else:
            raise itsdangerous.SignatureExpired(
                'Signature age %s < %s ' % (timestamp, now),
                payload=value,
                date_signed=timestamp)
    else:
        s = itsdangerous.URLSafeSerializer(secret_key=__CRYPT.get("secret_key"), salt=__CRYPT.get("salt"), **kw)
        return s.loads(token) 
Example #12
Source File: local.py    From cloudstorage with MIT License 6 votes vote down vote up
def validate_signature(self, signature):
        """Validate signed signature and return payload if valid.

        :param signature: Signature.
        :type signature: str

        :return: Deserialized signature payload.
        :rtype: dict

        :raises SignatureExpiredError: If the signature has expired.
        """
        serializer = self._make_serializer()
        payload = serializer.loads(signature, max_age=None)
        max_age = payload.get("max_age", 0)

        # https://github.com/pallets/itsdangerous/issues/43
        try:
            return serializer.loads(signature, max_age=max_age)
        except itsdangerous.SignatureExpired:
            raise SignatureExpiredError 
Example #13
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 #14
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 #15
Source File: test_verify.py    From notifications-admin with MIT License 5 votes vote down vote up
def test_verify_email_redirects_to_email_sent_if_token_expired(
    client,
    mocker,
    api_user_pending,
):
    mocker.patch('app.main.views.verify.check_token', side_effect=SignatureExpired('expired'))

    response = client.get(url_for('main.verify_email', token='notreal'))

    assert response.status_code == 302
    assert response.location == url_for('main.resend_email_verification', _external=True) 
Example #16
Source File: user.py    From flask-base with MIT License 5 votes vote down vote up
def confirm_account(self, token):
        """Verify that the provided token is for this user's id."""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except (BadSignature, SignatureExpired):
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        db.session.commit()
        return True 
Example #17
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 #18
Source File: token_auth.py    From python-admin with MIT License 5 votes vote down vote up
def get_auth_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except SignatureExpired:
        return False
    except BadSignature:
        return False

    return data 
Example #19
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 #20
Source File: user_management_test.py    From golem with MIT License 5 votes vote down vote up
def test_verify_auth_token_expired_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()
        user = Users.get_user_by_username(username)
        token = user.generate_auth_token(app.secret_key, expiration=1)
        time.sleep(2)
        with pytest.raises(SignatureExpired):
            Users.verify_auth_token(app.secret_key, token) 
Example #21
Source File: user.py    From penn-club-ratings with MIT License 5 votes vote down vote up
def confirm_account(self, token):
        """Verify that the provided token is for this user's id."""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except (BadSignature, SignatureExpired):
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        db.session.commit()
        return True 
Example #22
Source File: user.py    From BhagavadGita with GNU General Public License v3.0 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 #23
Source File: auth.py    From em-slack-tableflip with MIT License 5 votes vote down vote up
def validate_state(state):
    """Validate state token returned by authentication."""
    try:
        # Attempt to decode state
        state_token = GENERATOR.loads(
            state,
            max_age=timedelta(minutes=60).total_seconds()
        )

    except SignatureExpired:
        # Token has expired
        report_event('token_expired', {
            'state': state
        })
        abort(400)

    except BadSignature:
        # Token is not authorized
        report_event('token_not_authorized', {
            'state': state
        })
        abort(401)

    if state_token != PROJECT_INFO['client_id']:
        # Token is not authorized
        report_event('token_not_valid', {
            'state': state,
            'state_token': state_token
        })
        abort(401) 
Example #24
Source File: user.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def confirm_account(self, token):
        """Verify that the provided token is for this user's id."""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except (BadSignature, SignatureExpired):
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        db.session.commit()
        return True 
Example #25
Source File: views.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def confirm_shloka(id, token):
    """Confirm new subscription with provided token."""
    vrindavan_id = id
    current_app.logger.info(vrindavan_id)
    sql = """
        SELECT confirmed
        FROM vrindavan
        WHERE vrindavan_id = %s
    """ % (vrindavan_id)
    result = db.session.execute(sql)
    confirmed = [d['confirmed'] for d in result][0]
    current_app.logger.info(confirmed)

    if confirmed:
        return redirect(url_for('main.index'))
    if not confirmed:
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except (BadSignature, SignatureExpired):
            return False
        if data.get('confirm') != vrindavan_id:
            return False
        sql = """
            UPDATE vrindavan
            SET confirmed = 'true'
            WHERE vrindavan_id = %s
        """ % (vrindavan_id)
        db.session.execute(sql)
        db.session.commit()
        flash('Your subscription has been confirmed.', 'success')
    else:
        flash('The confirmation link is invalid or has expired.', 'error')
    return redirect(url_for('main.index')) 
Example #26
Source File: views.py    From MPContribs with MIT License 5 votes vote down vote up
def applications(token, action):
    ts = current_app.config["USTS"]
    max_age = current_app.config["USTS_MAX_AGE"]
    try:
        owner, project = ts.loads(token, max_age=max_age)
    except SignatureExpired:
        return f"signature for {owner} of {project} expired."

    try:
        obj = Projects.objects.get(project=project, owner=owner, is_approved=False)
    except DoesNotExist:
        return f"{project} for {owner} already approved or denied."

    actions = ["approve", "deny"]
    if action not in actions:
        response = f"<h3>{project}</h3><ul>"
        scheme = "http" if current_app.config["DEBUG"] else "https"
        for a in actions:
            u = url_for(
                "projects.applications",
                token=token,
                action=a,
                _scheme=scheme,
                _external=True,
            )
            response += f'<li><a href="{u}">{a}</a></li>'
        return response + "</ul>"

    if action == "approve":
        obj.is_approved = True
        obj.save()  # post_save (created=False) sends notification when `is_approved` set
    else:
        obj.delete()  # post_delete signal sends notification

    return f'{project} {action.replace("y", "ie")}d and {owner} notified.' 
Example #27
Source File: test_new_password.py    From notifications-admin with MIT License 5 votes vote down vote up
def test_should_redirect_to_forgot_password_with_flash_message_when_token_is_expired(
    app_,
    client,
    mock_login,
    mocker
):
    mocker.patch('app.main.views.new_password.check_token', side_effect=SignatureExpired('expired'))
    token = generate_token('foo@bar.com', app_.config['SECRET_KEY'], app_.config['DANGEROUS_SALT'])

    response = client.get(url_for_endpoint_with_token('.new_password', token=token))

    assert response.status_code == 302
    assert response.location == url_for('.forgot_password', _external=True) 
Example #28
Source File: new_password.py    From notifications-admin with MIT License 5 votes vote down vote up
def new_password(token):
    try:
        token_data = check_token(token, current_app.config['SECRET_KEY'], current_app.config['DANGEROUS_SALT'],
                                 current_app.config['EMAIL_EXPIRY_SECONDS'])
    except SignatureExpired:
        flash('The link in the email we sent you has expired. Enter your email address to resend.')
        return redirect(url_for('.forgot_password'))

    email_address = json.loads(token_data)['email']
    user = User.from_email_address(email_address)
    if user.password_changed_more_recently_than(json.loads(token_data)['created_at']):
        flash('The link in the email has already been used')
        return redirect(url_for('main.index'))

    form = NewPasswordForm()

    if form.validate_on_submit():
        user.reset_failed_login_count()
        session['user_details'] = {
            'id': user.id,
            'email': user.email_address,
            'password': form.new_password.data}
        if user.auth_type == 'email_auth':
            # they've just clicked an email link, so have done an email auth journey anyway. Just log them in.
            return log_in_user(user.id)
        else:
            # send user a 2fa sms code
            user.send_verify_code()
            return redirect(url_for('main.two_factor'))
    else:
        return render_template('views/new-password.html', token=token, form=form, user=user) 
Example #29
Source File: test_user.py    From huskar with MIT License 5 votes vote down vote up
def test_parse_expired_token(user_foo, is_app):
    token = user_foo.generate_token('42', expires_in=100)
    assert user_foo.get_by_token('42', token) is user_foo

    with freeze_time('9999-12-31 23:59:59'):
        assert user_foo.get_by_token('42', token) is None

    with raises(SignatureExpired), freeze_time('9999-12-31 23:59:59'):
        user_foo.get_by_token('42', token, raises=True) 
Example #30
Source File: user.py    From huskar with MIT License 5 votes vote down vote up
def _load_token(secret_key, token, raises):
    s = itsdangerous.TimedJSONWebSignatureSerializer(secret_key)
    try:
        payload = s.loads(token)
    except (itsdangerous.BadSignature, itsdangerous.SignatureExpired):
        if raises:
            raise
        return
    return payload['username']