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


Python TimestampSigner.unsign方法代码示例

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


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

示例1: __init__

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
class Auth:

    @classmethod
    def __init__(self, app):
        self.signer = TimestampSigner(app.config['SECRET_KEY'])
        self.app = app

    @classmethod
    def requires_login(self, f):
        @wraps(f)
        def decorated(*args, **kwargs):
            authentication_token = request.headers.get('Authentication-Token')

            if not authentication_token or not self.__is_token_valid(
                    authentication_token):
                return response(
                    status=401,
                    message='Not authorized'
                )

            return f(*args, **kwargs)

        return decorated

    @staticmethod
    def hash_password(password):
        return hashlib.sha256(password).hexdigest()

    @classmethod
    def generate_auth_token(self):
        token_random_string = ''.join(
            choice(ascii_letters) for i in range(
                self.app.config['TOKEN_RANDOM_STRING_LENGTH']))

        return self.signer.sign(token_random_string)

    @classmethod
    def __is_token_valid(self, authentication_token):
        try:
            self.signer.unsign(
                authentication_token,
                max_age=self.app.config['TOKEN_VALIDITY_DURATION']
            )

        except SignatureExpired as e:
            self.app.logger.info('INFO: SignatureExpired, %s', str(e))
            return False    # valid token, but expired
        except BadSignature as e:
            self.app.logger.info('INFO: BadSignature, %s', str(e))
            return False    # invalid token

        return True
开发者ID:khazra,项目名称:python-api,代码行数:54,代码来源:auth.py

示例2: verifyCdata

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def verifyCdata(cdata, secretkey, mxtime):
  s = TimestampSigner(secretkey)
  try: 
    string = s.unsign(cdata, max_age=mxtime)
    return string 
  except: 
    return False
开发者ID:mose,项目名称:cloudroutes-service,代码行数:9,代码来源:cookies.py

示例3: reset_user_password_step_two

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def reset_user_password_step_two(form):
    """
    second step of the password reset: check that the hash matches the temp password, force the change on ads classic
    """
    #create an itsdangerous object to sign the verification email and encrypt the password
    itsd = TimestampSigner(config.ACCOUNT_VERIFICATION_SECRET)
    reset_code = form.resetcode.data
    try:
        code = itsd.unsign(reset_code, max_age=10800) #code valid only 3 hours
    except BadTimeSignature:
        app.logger.error('User password reset error: used reset code not valid. Email used: %s ; reset code: %s' % (form.login.data, reset_code))
        return False, 'The reset code is not valid.', 'error'
    except SignatureExpired:
        app.logger.error('User password reset error: used reset code expired. Email used: %s ; reset code: %s' % (form.login.data, reset_code))
        return False, 'The reset code has expired. Please request a new one.', 'error'
    
    #check if the reset code is the same stored in the DB
    loc_db_user = AdsUserRecord.query.filter(AdsUserRecord.username==form.login.data) #@UndefinedVariable
    #get the user object
    user_rec = loc_db_user.first()
    if reset_code != user_rec.password:
        app.logger.error('User password reset error: used valid reset code but it doesn\'t match the one in the DB. Email used: %s ; reset code: %s' % (form.login.data, reset_code))
        return False, 'The reset code is not valid.', 'error'
    else:
        #proceed with the actual reset
        classic_user = reset_classic_password(form.login.data, form.new_password.data)
        if classic_user and classic_user.get('message') == 'ACCOUNT_UPDATED':
            #remove the reset code from the password field of the local db
            loc_db_user.set(password='').execute()
            return True, 'Password successfully updated.', 'success'
        else:
            app.logger.error('ADS Classic account modification error: return message not expected. Tried to force update password: login %s' % form.login.data)
            return False, 'Problems in the account modification. Please try again.', 'error'
开发者ID:ehenneken,项目名称:adsabs,代码行数:35,代码来源:user.py

示例4: get

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
 def get(self):
     args = get_parser('activation').parse_args()
     serial = args['serial']
     change_email = redis.get('change_email:{}'.format(serial))
     if not change_email:
         return make_response(redirect('/#!/?error=激活码无效'))
     change_email = change_email.decode()
     signer = TimestampSigner(
         current_app.config['SECRET_KEY'], salt='change_email')
     try:
         username = signer.unsign(
             base64.b64decode(serial.encode('utf-8')),
             max_age=172800).decode('utf-8')
         user = User.query.filter_by(username=username).first()
         if not user:
             return make_response(redirect('/#!/?error=激活码无效'))
         authentication = db_session.query(Authentication).filter(
             AuthenticationType.logic == 'email',
             Authentication.type_id == AuthenticationType.id,
             Authentication.user_id == user.id).first()
         authentication.accept()
         authentication.fields[0].value = change_email
         user.email = change_email
         redis.delete('change_email:{}'.format(serial))
         db_session.commit()
     except (itsdangerous.BadSignature, itsdangerous.SignatureExpired):
         abort(400, message='激活码无效')
     else:
         return make_response(redirect('/#!/?success=修改邮箱成功'))
开发者ID:xxguo,项目名称:leopard,代码行数:31,代码来源:authentication.py

示例5: register_user

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def register_user():
    data = request.form
    if not (data['full_name'] or data['email']):
        return 'Bad Request', 404
    signed_data = request.headers['Authorisation']
    client_key = app.config['WWW_CLIENT_KEY']
    signer = TimestampSigner(client_key, digest_method=hashlib.sha256)
    try:
        unsigned = signer.unsign(signed_data, max_age=5)
        client_id, email, full_name = unsigned.decode('utf-8').split(':')
        if client_id != app.config['WWW_CLIENT_ID']:
            raise Exception
        if email != data['email']:
            raise Exception
        if full_name != data['full_name']:
            raise Exception
    except Exception as ex:
        log_traceback(current_app.logger, ex)
        return 'Unauthorized', 401

    person = registers.Person()
    person.born_at = datetime.fromtimestamp(mktime(gmtime(0)))
    person.full_name = full_name
    person.save()

    random_temp_password = uuid4().hex
    user = auth.AuthUser.create_user(email, random_temp_password)
    user.person_uri = person.uri
    user.save()

    return 'Created', 201
开发者ID:sausages-of-the-future,项目名称:registry,代码行数:33,代码来源:views.py

示例6: update_user_password

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def update_user_password():
    email = request.form.get('email')
    if not email:
        return 'Bad Request', 404
    signed_data = request.headers['Authorisation']
    client_key = app.config['WWW_CLIENT_KEY']
    signer = TimestampSigner(client_key, digest_method=hashlib.sha256)
    try:
        unsigned = signer.unsign(signed_data, max_age=5)
        client_id, user_email, password = unsigned.decode('utf-8').split(':')
        if client_id != app.config['WWW_CLIENT_ID']:
            raise Exception
        if email != user_email:
            raise Exception

        user = AuthUser.objects.filter(email=email).first()
        if not user:
            abort(404)
        else:
            user.set_password(password)
            user.save()
            return 'OK', 200

    except Exception as ex:
        log_traceback(current_app.logger, ex)
        return 'Unauthorized', 401
开发者ID:sausages-of-the-future,项目名称:registry,代码行数:28,代码来源:views.py

示例7: email_check

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def email_check():
    """
    校验邮箱有效性
    http://localhost:5000/email/[email protected]
    """
    sign = request.args.get('sign', '')
    from itsdangerous import TimestampSigner, SignatureExpired, BadTimeSignature
    s = TimestampSigner(app.config['SECRET_KEY'])
    try:
        # email = s.unsign(sign, max_age=5)  # 5秒过期
        email = s.unsign(sign, max_age=30*24*60*60)  # 1个月过期
        # return email
        # 校验通过,更新邮箱验证状态
        from user_auth import update_user_auth_rows
        result = update_user_auth_rows({'verified': 1}, **{'auth_type': 'email', 'auth_key': email})
        if result == 1:
            flash(u'%s, Your mailbox has been verified' % email, 'success')
            return redirect(url_for('login'))
        else:
            flash(u'%s, Sorry, Your mailbox validation failed' % email, 'warning')
    except SignatureExpired as e:
        # 处理签名超时
        flash(e.message, 'warning')
    except BadTimeSignature as e:
        # 处理签名错误
        flash(e.message, 'warning')
    return redirect(url_for('reg'))
开发者ID:zhanghe06,项目名称:flask_project,代码行数:29,代码来源:views.py

示例8: Tokenizer

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
class Tokenizer(object):
    """
    A class for creating cryptographically signed tokens used by CivID.

    >>> tokenizer = Tokenizer('123')
    >>> lt = tokenizer.create_login_token('gatzy')
    >>> tokenizer.validate_login_token(lt)
    'gatzy'
    >>> ic = tokenizer.create_identity_code('ttk2')
    >>> tokenizer.validate_identity_code(ic)
    'ttk2'
    """
    def __init__(self, signing_key):
        self.key = signing_key
        self.signer = TimestampSigner(signing_key)

    def short_sig(self, string):
        """
        Returns a token computed from truncating the hash of the given
        string with the signing key.
        """
        return base64.urlsafe_b64encode(
            hashlib.sha256(self.key + string).digest()
        )[:SHORT_SIG_LENGTH]

    def create_login_token(self, username):
        """
        Creates a login token of the form "signatureUsername".
        This token is bound to a UNIX timestamp divided by LOGIN_WINDOW_S,
        but it is not stored within the token in order to limit its length.
        """
        return self.short_sig(username + now_str()) + username

    def validate_login_token(self, token):
        if len(token) < SHORT_SIG_LENGTH + MIN_USERNAME_LENGTH:
            raise InvalidTokenError("Malformed token")

        signature = token[0:SHORT_SIG_LENGTH]
        user = token[SHORT_SIG_LENGTH:]
        
        if (
            signature != self.short_sig(user + now_str()) and 
            signature != self.short_sig(user + last_period_str())
        ):
            raise InvalidTokenError("Login link invalid or expired")

        return user

    def create_identity_code(self, username):
        # Identity codes contain this silly "scrambled" version of the username
        # to discourage naive implementations from parsing it out of the code
        # without making a request to validate it against the CivID server.
        return self.signer.sign(scramble_username(username))

    def validate_identity_code(self, code):
        try:
            return unscramble_username(self.signer.unsign(code, max_age=CODE_WINDOW_S))
        except:
            raise InvalidCodeError()
开发者ID:tdeck,项目名称:civid_web,代码行数:61,代码来源:tokens.py

示例9: TokenManager

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
class TokenManager(object):
    def setup(self, secret):
        """ Create a cypher to encrypt IDs and a signer to sign tokens."""
        # Create cypher to encrypt IDs
        key = secret + '0123456789abcdef'  # ensure >=16 characters
        sixteen_byte_key = key[0:16]  # get first 16 characters
        self.cipher = AES.new(sixteen_byte_key)

        # Create signer to sign tokens
        self.signer = TimestampSigner(secret)

    def encrypt_id(self, id):
        """ Encrypts integer ID to url-safe base64 string."""
        str1 = '%016d' % id                             # --> 16 byte integer string
        str2 = self.cipher.encrypt(str1)                # --> encrypted data
        str3 = base64.urlsafe_b64encode(str2)           # --> URL safe base64 string with '=='
        return str3[0:-2]                               # --> base64 string without '=='

    def decrypt_id(self, encrypted_id):
        """ Decrypts url-safe base64 string to integer ID"""
        # In Python3, encrypted_id is <type 'str'> and needs to be converted to bytes
        if type(encrypted_id)=='str':   # pragma: no cover
            encrypted_id = encrypted_id.encode('ascii')

        try:
            str3 = encrypted_id + b'=='             # --> base64 string with '=='
            str2 = base64.urlsafe_b64decode(str3)   # --> encrypted data
            str1 = self.cipher.decrypt(str2)        # --> 16 byte integer string
            return int(str1)                        # --> integer id
        except Exception as e:                      # pragma: no cover
            print('!!!Exception in decrypt_id!!!')
            return 0

    def generate_token(self, id):
        """ Return token with id, timestamp and signature"""
        # In Python3 we must make sure that bytes are converted to strings.
        # Hence the addition of '.decode()'
        return self.signer.sign(self.encrypt_id(id)).decode()

    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:P2PTeam,项目名称:Flask-User,代码行数:60,代码来源:tokens.py

示例10: _check_token

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def _check_token(token):
    from itsdangerous import TimestampSigner, SignatureExpired
    signer = TimestampSigner(app.config['SECRET_KEY'])
    try:
        email = signer.unsign(token, max_age=app.config['TOKEN_MAX_AGE_SECONDS'])
        return email
    except SignatureExpired as e:
        current_app.logger.info('token expired %s' % e)
        return None
开发者ID:sausages-of-the-future,项目名称:www,代码行数:11,代码来源:views.py

示例11: load_user_from_request

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def load_user_from_request(request):
    authorization = request.headers.get('Authorization')
    if authorization is None or not authorization.startswith('Bearer '):
        return None
    token = authorization.split(' ', 1)[-1]
    signer = TimestampSigner(app.secret_key)
    id = signer.unsign(token)
    user = User.query.get(int(id))
    return user
开发者ID:fiveandsix,项目名称:server,代码行数:11,代码来源:auth.py

示例12: __init__

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
    def __init__(self, request):
        self.__acl__ = []
        config = request.registry.settings
        req_url_secret = request.params.get("secret")
        req_secret = request.headers.get("x-channelstream-secret", req_url_secret)

        addr = request.environ["REMOTE_ADDR"]
        if not is_allowed_ip(addr, config):
            log.warning("IP: {} is not whitelisted".format(addr))
            return

        if req_secret:
            max_age = 60 if config["validate_requests"] else None
            signer = TimestampSigner(config["secret"])
            signer.unsign(req_secret, max_age=max_age)
        else:
            return
        self.__acl__ = [(Allow, Everyone, ALL_PERMISSIONS)]
开发者ID:AppEnlight,项目名称:channelstream,代码行数:20,代码来源:wsgi_security.py

示例13: decrypt

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def decrypt(string, max_age=15000):
    """
    This method will return decrypted version of an encrypted string.
    If age of encryption is greater than max age it will return False
    """
    try:
        signer = TimestampSigner(encrypt_key)
        return signer.unsign(string, max_age=max_age)
    except:
        return False
开发者ID:andela-snwuguru,项目名称:bucketlist-api,代码行数:12,代码来源:helper.py

示例14: get_api_key

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
def get_api_key(request):
    try:
        api_key_name = request.POST.get('api_key', '')
    except AttributeError:
        api_key_name = request.form.get('api_key', '')

    # There is probably a better way to do this.
    api_keys = ApiKey.all()
    api_key = None
    for ak in api_keys:
        if api_key_name.startswith(ak.name):
            try:
                s = TimestampSigner(ak.key)
                s.unsign(api_key_name, max_age=120)
                api_key = ak
            except SignatureExpired:
                pass

    return api_key
开发者ID:smeggingsmegger,项目名称:flask-cookiecutter,代码行数:21,代码来源:controls.py

示例15: verify_auth_token

# 需要导入模块: from itsdangerous import TimestampSigner [as 别名]
# 或者: from itsdangerous.TimestampSigner import unsign [as 别名]
	def verify_auth_token(token):
		s = TimestampSigner(current_app.config['SECRET_KEY'])
		try:
			id = s.unsign(token, max_age=3600)
		except SignatureExpired:
			return None # valid token, but expired
		except BadSignature:
			return None # invalid token

		user = User.query.get(id)
		return user
开发者ID:nisnaker,项目名称:rsscat,代码行数:13,代码来源:user.py


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