distribusi-verse/verse/statuspengguna/forgotpassword.py

59 lines
1.9 KiB
Python
Raw Permalink Normal View History

2022-03-27 16:07:44 +02:00
from uuid import uuid1
from datetime import datetime
from sqlalchemy.exc import (
DataError,
DatabaseError,
InterfaceError,
InvalidRequestError,
)
from flask import render_template
2022-03-27 16:07:44 +02:00
from flask_mail import Message
from usermodel import User
from forms.forgotpasswordform import ForgotPasswordForm
2022-03-27 16:07:44 +02:00
from app import db
def ForgotPassword(mail):
forgotpasswordform = ForgotPasswordForm()
if forgotpasswordform.validate_on_submit():
user = User.query.filter_by(
email=forgotpasswordform.email.data
).first()
if user is not None:
2022-03-27 16:07:44 +02:00
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(
"forgotpassword.html", forgotpasswordform=forgotpasswordform
)
2022-03-27 16:07:44 +02: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(
"Distribusiverse Forgotten Password ",
sender=("Distribusiverse mailer", "test@this.com"),
recipients=[user.email],
)
2022-03-27 16:07:44 +02:00
msg.html = f"""{user.username} has requested a password reset for
Distribusiverse.<br><hr>
<a href='http://localhost:5000/resetpassword/{resethash}'>Click here to
reset your password.</a>"""
mail.send(msg)