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


Python itsdangerous.SignatureExpired方法代码示例

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


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

示例1: unsign_data

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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) 
开发者ID:mardix,项目名称:assembly,代码行数:26,代码来源:asm.py

示例2: password_reset

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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') 
开发者ID:certsocietegenerale,项目名称:fame,代码行数:23,代码来源:views.py

示例3: get_token_status

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [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

示例4: verify_token

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [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

示例5: verify_email

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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')) 
开发者ID:alphagov,项目名称:notifications-admin,代码行数:27,代码来源:verify.py

示例6: two_factor_email

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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) 
开发者ID:alphagov,项目名称:notifications-admin,代码行数:24,代码来源:two_factor.py

示例7: change_email

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [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

示例8: verify_auth_token

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [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

示例9: get

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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 
开发者ID:ScrappyZhang,项目名称:ecommerce_website_development,代码行数:25,代码来源:views.py

示例10: validate_signature

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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 
开发者ID:scottwernervt,项目名称:cloudstorage,代码行数:22,代码来源:local.py

示例11: auth_required

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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 
开发者ID:golemhq,项目名称:golem,代码行数:21,代码来源:api.py

示例12: applications

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
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.' 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:37,代码来源:views.py

示例13: confirm

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
def confirm(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None
        except BadSignature:
            return None
        developer = Developer.query.get(data['confirm'])
        return developer 
开发者ID:jpush,项目名称:jbox,代码行数:12,代码来源:models.py

示例14: decode_single_use_JWS

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
def decode_single_use_JWS(cls, token, required_type):

        try:
            s = TimedJSONWebSignatureSerializer(
                current_app.config['SECRET_KEY'])

            data = s.loads(token.encode("utf-8"))

            user_id = data.get('id')

            token_type = data.get('type')

            if token_type != required_type:
                return {'success': False, 'message': 'Wrong token type (needed %s)' % required_type}

            if not user_id:
                return {'success': False, 'message': 'No User ID provided'}

            user = cls.query.filter_by(
                id=user_id).execution_options(show_all=True).first()

            if not user:
                return {'success': False, 'message': 'User not found'}

            return {'success': True, 'user': user}

        except BadSignature:

            return {'success': False, 'message': 'Token signature not valid'}

        except SignatureExpired:

            return {'success': False, 'message': 'Token has expired'}

        except Exception as e:

            return {'success': False, 'message': e} 
开发者ID:teamsempo,项目名称:SempoBlockchain,代码行数:39,代码来源:user.py

示例15: get_token_status

# 需要导入模块: import itsdangerous [as 别名]
# 或者: from itsdangerous import SignatureExpired [as 别名]
def get_token_status(token, serializer, max_age=None, return_data=False):
    """Get the status of a token.

    :param token: The token to check
    :param serializer: The name of the seriailzer. Can be one of the
                       following: ``confirm``, ``login``, ``reset``
    :param max_age: The name of the max age config option. Can be on of
                    the following: ``CONFIRM_EMAIL``, ``LOGIN``,
                    ``RESET_PASSWORD``
    """
    serializer = getattr(_security, serializer + "_serializer")
    max_age = get_max_age(max_age)
    user, data = None, None
    expired, invalid = False, False

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

    if data:
        user = _datastore.find_user(fs_uniquifier=data[0])

    expired = expired and (user is not None)

    if return_data:
        return expired, invalid, user, data
    else:
        return expired, invalid, user 
开发者ID:Flask-Middleware,项目名称:flask-security,代码行数:34,代码来源:utils.py


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