from itsdangerous import BadSignature, SignatureExpired from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
def generate_token(user, operation, expire_in=None, **kwargs): s = Serializer(current_app.config['SECRET_KEY'], expire_in)
代码语言:javascript复制data = {'id': user.id, 'operation': operation}
data.update(**kwargs)
return s.dumps(data)
def validate_token(user, token, operation, new_password=None): s = Serializer(current_app.config['SECRET_KEY'])
代码语言:javascript复制try:
data = s.loads(token)
except (SignatureExpired, BadSignature):
return False
if operation != data.get('operation') or user.id != data.get('id'):
return False
if operation == Operations.CONFIRM:
user.confirmed = True
elif operation == Operations.RESET_PASSWORD:
user.set_password(new_password)
elif operation == Operations.CHANGE_EMAIL:
new_email = data.get('new_email')
if new_email is None:
return False
if User.query.filter_by(email=new_email).first() is not None:
return False
user.email = new_email
else:
return False
db.session.commit()
return True
token = generate_token(user=user, operation='confirm') send_confirm_email(user=user, token=token)
代码语言:javascript复制if validate_token(user=current_user, token=token, operation=Operations.CONFIRM):
flash('Account confirmed.', 'success')
return redirect(url_for('main.index'))