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')
python类BadTimeSignature()的实例源码
def get(self, request, *args, **kwargs):
if request.GET.get('key'):
serializer = URLSafeTimedSerializer(settings.SECRET_KEY)
try:
user_id = serializer.loads(
request.GET.get('key'),
max_age=60 * 2, # Signature expires after 2 minutes
)
user = get_object_or_404(User, id=user_id)
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return redirect('home')
except (BadSignature, BadTimeSignature):
return redirect('login')
return super().get(request, *args, **kwargs)
def reset_password(data=None):
if data is not None and request.method == "GET":
return render_template('reset_password.html', mode='set')
if data is not None and request.method == "POST":
try:
s = TimedSerializer(app.config['SECRET_KEY'])
name = s.loads(data.decode('base64'), max_age=1800)
except BadTimeSignature:
return render_template('reset_password.html', errors=['Your link has expired'])
team = Teams.query.filter_by(name=name).first()
team.password = bcrypt_sha256.encrypt(request.form['password'].strip())
db.session.commit()
db.session.close()
return redirect('/login')
if request.method == 'POST':
email = request.form['email'].strip()
team = Teams.query.filter_by(email=email).first()
if not team:
return render_template('reset_password.html', errors=['Check your email'])
s = TimedSerializer(app.config['SECRET_KEY'])
token = s.dumps(team.name)
text = """
Did you initiate a password reset?
{0}/reset_password/{1}
""".format(app.config['HOST'], token.encode('base64'))
sendmail(email, text)
return render_template('reset_password.html', errors=['Check your email'])
return render_template('reset_password.html')
def check_token(self, token_sign):
"""
?? token, ?????? token
"""
from itsdangerous import TimestampSigner, SignatureExpired, BadTimeSignature
s = TimestampSigner(self._sign_key)
try:
token = s.unsign(token_sign, max_age=60) # 60???
return {'success': token}
except SignatureExpired as e:
# ??????
return {'error': e.message}
except BadTimeSignature as e:
# ??????
return {'error': e.message}
def load_token(token):
"""
Flask-Login token_loader callback.
The token_loader function asks this function to take the token that was
stored on the users computer process it to check if its valid and then
return a User Object if its valid or None if its not valid.
:param token: Token generated by :meth:`app.models.User.get_auth_token`
"""
# The Token itself was generated by User.get_auth_token. So it is up to
# us to known the format of the token data itself.
# The Token was encrypted using itsdangerous.URLSafeTimedSerializer which
# allows us to have a max_age on the token itself. When the cookie is
# stored
# on the users computer it also has a exipry date, but could be changed by
# the user, so this feature allows us to enforce the exipry date of the
# token
# server side and not rely on the users cookie to exipre.
max_age = current_app.config['REMEMBER_COOKIE_DURATION'].total_seconds()
# Decrypt the Security Token, data = [username, hashpass, id]
s = URLSafeTimedSerializer(
current_app.config['SECRET_KEY'],
salt='user-auth',
signer_kwargs=dict(key_derivation='hmac',
digest_method=hashlib.sha256))
try:
data = s.loads(token, max_age=max_age)
except (BadTimeSignature, SignatureExpired):
return None
# Find the User
user = User.query.get(data[2])
# 2FA check
totp_endpoint = request.endpoint == 'auth.verify_totp'
if user and user.otp_enabled and not totp_endpoint and len(data) < 4:
return None
# Check Password and return user or None
if user and data[1] == user._password:
return user
return None