當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。