本文整理汇总了Python中itsdangerous.TimestampSigner类的典型用法代码示例。如果您正苦于以下问题:Python TimestampSigner类的具体用法?Python TimestampSigner怎么用?Python TimestampSigner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TimestampSigner类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register_user
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
示例2: verifyCdata
def verifyCdata(cdata, secretkey, mxtime):
s = TimestampSigner(secretkey)
try:
string = s.unsign(cdata, max_age=mxtime)
return string
except:
return False
示例3: email_check
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'))
示例4: update_user_password
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
示例5: confirm_account
def confirm_account(token):
email = _check_token(token).decode('utf8')
form = forms.SetPasswordForm()
user = models.InviteApplicant.objects.filter(email=email).first()
if not email:
current_app.logger.info('token has expired.')
flash('Link has expired', 'error')
else:
if user.password_set:
flash('Account already confirmed and password set')
return render_template('done.html', message='Account already confirmed and password set')
if form.validate_on_submit():
password = form.password.data
www_id = app.config['WWW_CLIENT_ID']
www_key = app.config['WWW_CLIENT_KEY']
to_sign = '%s:%s:%s' % (www_id, email, password)
signer = TimestampSigner(www_key, digest_method=hashlib.sha256)
signed = signer.sign(to_sign)
headers = { 'Authorisation': signed }
url = '%s/update-user-password' % app.config['REGISTRY_BASE_URL']
resp = requests.post(url, data={'email': email}, headers=headers)
if resp.status_code == 200:
user = models.InviteApplicant.objects.filter(email=email).first()
user.password_set = True
user.save()
flash('Your password has been updated')
return render_template('done.html', message='Your password has been updated')
else:
flash('Failed to set new password in registry', 'error')
return render_template('set_account_password.html', form=form, token=token, user=user)
示例6: get
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=修改邮箱成功'))
示例7: reset_user_password_step_two
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'
示例8: make_server_request
def make_server_request(request, payload, endpoint, auth=None, method="post"):
"""
makes a json request to channelstream server endpoint signing the request and sending the payload
:param request:
:param payload:
:param endpoint:
:param auth:
:return:
"""
server_port = request.registry.settings["port"]
signer = TimestampSigner(request.registry.settings["secret"])
sig_for_server = signer.sign("channelstream")
if not six.PY2:
sig_for_server = sig_for_server.decode("utf8")
secret_headers = {
"x-channelstream-secret": sig_for_server,
"Content-Type": "application/json",
}
url = "http://127.0.0.1:%s%s" % (server_port, endpoint)
response = getattr(requests, method)(
url, data=json.dumps(payload), headers=secret_headers, auth=auth
)
if response.status_code >= 400:
log.error(response.text)
response.raise_for_status()
return response
示例9: verify_timed_token
def verify_timed_token(token):
s = TimestampSigner(SECRET_KEY)
try:
data = s.loads(token)
except (SignatureExpired, BadSignature):
return None
return data
示例10: Tokenizer
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()
示例11: create_token
def create_token(self):
"""
生成 token (基于 uuid)
"""
from uuid import uuid1
from itsdangerous import TimestampSigner
s = TimestampSigner(self._sign_key)
return s.sign(str(uuid1()))
示例12: encrypt
def encrypt(self, payload, timestamp=False):
result = ''
s1 = URLSafeSerializer(self.secret_key)
result = s1.dumps(payload)
if(timestamp == True):
s2 = TimestampSigner(self.secret_key)
result = s2.sign(result)
return result
示例13: sign
def sign(self, session_id):
"""
签名 session_id
:param session_id:
:return:
"""
s = TimestampSigner(self._sign_key)
return s.sign(session_id)
示例14: TokenManager
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)
示例15: load_user_from_request
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