distribusi-verse: medium-tech web app content management system for the web
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.2 KiB

from datetime import datetime
from uuid import uuid1
from flask import Blueprint, render_template
from flask_mail import Mail, Message
from sqlalchemy.exc import (
DatabaseError,
DataError,
InterfaceError,
InvalidRequestError,
)
from app import db, get_app
from forms.forgotpasswordform import ForgotPasswordForm
from models.user_model import User
mail = Mail(get_app())
forgot_password = Blueprint(
"forgotpassword",
__name__,
template_folder="templates/statuspengguna",
static_folder="static",
)
@forgot_password.route("/", methods=["GET", "POST"])
def forgotpassword():
return ForgotPassword(mail)
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:
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
)
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],
)
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)