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

79 lines
2.5 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 flask import flash, redirect, render_template, url_for
from flask_bcrypt import generate_password_hash
from flask_login import login_user
2023-12-03 11:33:07 +01:00
from sqlalchemy.exc import (
DatabaseError,
2023-12-03 14:19:53 +01:00
DataError,
IntegrityError,
2023-12-03 11:33:07 +01:00
InterfaceError,
InvalidRequestError,
)
2023-12-03 14:19:53 +01:00
from werkzeug.routing import BuildError
2023-12-03 11:33:07 +01:00
from app import db
from application.forms.resetpasswordform import ResetPasswordForm
from application.models.usermodel import User
2023-12-03 11:33:07 +01:00
def ResetPassword(path):
linkvalid = False
user = User.query.filter_by(resethash=path).first()
if user is None:
return redirect(url_for("index"))
timepassed = datetime.now() - user.resettime
if timepassed.days < 1:
linkvalid = True
resetpasswordform = ResetPasswordForm()
if resetpasswordform.validate_on_submit():
return ResetUserPasswordInDB(user, resetpasswordform)
return render_template(
"resetpassword.html",
resetpasswordform=resetpasswordform,
path=path,
linkvalid=linkvalid,
)
def ResetUserPasswordInDB(user, resetpasswordform):
try:
newpassword = resetpasswordform.confirmpassword.data
user.password = generate_password_hash(newpassword)
user.resethash = None
user.resettime = None
db.session.commit()
flash("Password Succesfully updated", "success")
login_user(user)
return redirect(url_for("index"))
except InvalidRequestError:
db.session.rollback()
resetpasswordform.email.errors.append("Something went wrong!")
flash("Something went wrong!", "danger")
except IntegrityError:
db.session.rollback()
resetpasswordform.email.errors.append("User already exists!")
flash("User already exists!", "warning")
except DataError:
db.session.rollback()
resetpasswordform.email.errors.append("Invalid Entry")
flash("Invalid Entry", "warning")
except InterfaceError:
db.session.rollback()
resetpasswordform.email.errors.append(
"Error connecting to the database"
)
flash("Error connecting to the database", "danger")
except DatabaseError:
db.session.rollback()
resetpasswordform.email.errors.append(
"Error connecting to the database"
)
flash("Error connecting to the database", "danger")
except BuildError:
db.session.rollback()
resetpasswordform.email.errors.append("Unknown error occured!")
flash("An error occured !", "danger")