Answer the question
In order to leave comments, you need to log in
How to create a one-time token?
Good afternoon.
I want to add a password reset feature to a Flask site using JWT and the flask PyJWT package.
At the moment, you can request a letter several times in which there will be a link with a token, and after changing the password, the rest of the links with the token will remain valid. That is, it will also be possible to navigate through them and change the password further. I want to make sure that after clicking on the link with the token and resetting the password, all other links were already invalid (in the event that the user requested a lot of them).
Functions for creating and verifying a token:
def get_reset_password_token(self, expires_in=600):
return jwt.encode({'reset_password': self.id,
'exp': time() + expires_in},
app.config['SECRET_KEY'],
algorithm='HS256')
@staticmethod
def verify_reset_password_token(token):
try:
id = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password']
except:
return
return User.query.get(id)
Функция представления для изменения пароля:
@app.route('/reset_password/<token>', methods=['POST', 'GET'])
def reset_password(token):
if current_user.is_authenticated:
return redirect(url_for('/'))
user = User.verify_reset_password_token(token)
if not user:
return redirect(url_for('index'))
form = ResetPasswordForm()
if form.validate_on_submit():
user.set_password(form.password.data)
db.session.commit()
flash('Ваш пароль изменён')
return redirect(url_for('login'))
return render_template('reset_password.html',
form=form)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question