csv-library-website/library/application/user/forgotpassword.py

60 lines
1.9 KiB
Python
Raw Permalink Normal View History

2023-12-03 11:33:07 +01:00
from datetime import datetime
2023-12-03 14:19:53 +01:00
from uuid import uuid1
from flask import render_template
from flask_mail import Message
2023-12-03 11:33:07 +01:00
from sqlalchemy.exc import (
DatabaseError,
2023-12-03 14:19:53 +01:00
DataError,
2023-12-03 11:33:07 +01:00
InterfaceError,
InvalidRequestError,
)
from app import db
from application.forms.forgotpasswordform import ForgotPasswordForm
2024-03-30 12:00:47 +01:00
from application.models.usermodel import User
2023-12-03 11:33:07 +01:00
2024-03-30 18:09:04 +01:00
def ForgotPassword():
2023-12-03 11:33:07 +01:00
forgotpasswordform = ForgotPasswordForm()
if forgotpasswordform.validate_on_submit():
user = User.query.filter_by(
email=forgotpasswordform.email.data
).first()
if user is not None:
resethash = AddResetPasswordHash(user, forgotpasswordform)
ResetPassWordMessage(user, resethash, mail)
forgotpasswordform.email.errors.append(
f"""If {forgotpasswordform.email.data} exists, an email is send with
a password reset link. (If your inbox doesn't
contain any new mail, please check your spam folder.)"""
)
return render_template(
2024-03-30 18:09:04 +01:00
"user/forgotpassword.html", forgotpasswordform=forgotpasswordform
2023-12-03 11:33:07 +01:00
)
def AddResetPasswordHash(user, forgotpasswordform):
resethash = uuid1().hex
try:
user.resettime = datetime.now()
user.resethash = resethash
db.session.commit()
except (InvalidRequestError, DataError, InterfaceError, DatabaseError):
forgotpasswordform.email.errors.append("Something went wrong!")
db.session.rollback()
return resethash
def ResetPassWordMessage(user, resethash, mail):
msg = Message(
"Forgotten Password ",
sender=("mailer", "test@this.com"),
recipients=[user.email],
)
msg.html = f"""{user.username} has requested a password reset for
libary website.<br><hr>
<a href='http://localhost:5000/resetpassword/{resethash}'>Click here to
reset your password.</a>"""
mail.send(msg)