contentdb/app/blueprints/users/account.py

390 lines
13 KiB
Python
Raw Normal View History

# ContentDB
# Copyright (C) 2020 rubenwardy
#
# This program is free software: you can redistribute it and/or modify
2021-01-30 17:59:42 +01:00
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2021-01-30 17:59:42 +01:00
# GNU Affero General Public License for more details.
#
2021-01-30 17:59:42 +01:00
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-06-19 20:32:36 +02:00
import datetime
2024-06-02 22:17:15 +02:00
from flask import redirect, abort, render_template, flash, request, url_for, Response
2023-06-19 20:32:36 +02:00
from flask_babel import gettext, get_locale, lazy_gettext
from flask_login import current_user, login_required, logout_user, login_user
from flask_wtf import FlaskForm
from sqlalchemy import or_
2023-06-19 20:32:36 +02:00
from wtforms import StringField, SubmitField, BooleanField, PasswordField, validators
from wtforms.validators import InputRequired, Length, Regexp, DataRequired, Optional, Email, EqualTo
2020-12-06 16:02:02 +01:00
from app.tasks.emails import send_verify_email, send_anon_email, send_unsubscribe_verify, send_user_email
2023-06-19 22:27:49 +02:00
from app.utils import random_string, make_flask_login_password, is_safe_url, check_password_hash, add_audit_log, \
2024-06-02 22:17:15 +02:00
nonempty_or_none, post_login
from . import bp
2024-06-02 22:17:15 +02:00
from app.models import User, AuditSeverity, db, EmailSubscription, UserEmailVerification
from app.logic.users import create_user
class LoginForm(FlaskForm):
2022-01-07 22:55:33 +01:00
username = StringField(lazy_gettext("Username or email"), [InputRequired()])
password = PasswordField(lazy_gettext("Password"), [InputRequired(), Length(6, 100)])
remember_me = BooleanField(lazy_gettext("Remember me"), default=True)
submit = SubmitField(lazy_gettext("Sign in"))
def handle_login(form):
def show_safe_err(err):
if "@" in username:
2022-01-07 22:46:16 +01:00
flash(gettext("Incorrect email or password"), "danger")
else:
2020-12-04 23:29:10 +01:00
flash(err, "danger")
2020-12-04 23:29:10 +01:00
username = form.username.data.strip()
user = User.query.filter(or_(User.username == username, User.email == username)).first()
if user is None:
2022-01-07 22:46:16 +01:00
return show_safe_err(gettext(u"User %(username)s does not exist", username=username))
if not check_password_hash(user.password, form.password.data):
2022-01-07 22:46:16 +01:00
return show_safe_err(gettext(u"Incorrect password. Did you set one?"))
if not user.is_active:
2022-01-07 22:46:16 +01:00
flash(gettext("You need to confirm the registration email"), "danger")
return
2023-06-19 22:27:49 +02:00
add_audit_log(AuditSeverity.USER, user, "Logged in using password",
url_for("users.profile", username=user.username))
2020-12-09 21:38:36 +01:00
db.session.commit()
if not login_user(user, remember=form.remember_me.data):
2022-01-07 22:46:16 +01:00
flash(gettext("Login failed"), "danger")
return
return post_login(user, request.args.get("next"))
@bp.route("/user/login/", methods=["GET", "POST"])
def login():
next = request.args.get("next")
if next and not is_safe_url(next):
abort(400)
2020-12-05 00:07:19 +01:00
if current_user.is_authenticated:
2020-12-05 00:07:19 +01:00
return redirect(next or url_for("homepage.home"))
form = LoginForm(request.form)
if form.validate_on_submit():
ret = handle_login(form)
if ret:
return ret
2021-02-03 01:56:43 +01:00
if request.method == "GET":
form.remember_me.data = True
return render_template("users/login.html", form=form, next=next)
@bp.route("/user/logout/", methods=["GET", "POST"])
def logout():
logout_user()
return redirect(url_for("homepage.home"))
class RegisterForm(FlaskForm):
2023-06-19 22:27:49 +02:00
display_name = StringField(lazy_gettext("Display Name"), [Optional(), Length(1, 20)], filters=[nonempty_or_none])
2022-01-07 22:55:33 +01:00
username = StringField(lazy_gettext("Username"), [InputRequired(),
Regexp("^[a-zA-Z0-9._-]+$", message=lazy_gettext(
"Only alphabetic letters (A-Za-z), numbers (0-9), underscores (_), minuses (-), and periods (.) allowed"))])
2022-01-07 22:55:33 +01:00
email = StringField(lazy_gettext("Email"), [InputRequired(), Email()])
2023-08-26 15:54:58 +02:00
password = PasswordField(lazy_gettext("Password"), [InputRequired(), Length(12, 100)])
2022-01-07 22:55:33 +01:00
question = StringField(lazy_gettext("What is the result of the above calculation?"), [InputRequired()])
agree = BooleanField(lazy_gettext("I agree"), [DataRequired()])
submit = SubmitField(lazy_gettext("Register"))
def handle_register(form):
2021-04-17 03:08:54 +02:00
if form.question.data.strip().lower() != "19":
2022-01-07 22:46:16 +01:00
flash(gettext("Incorrect captcha answer"), "danger")
2021-04-17 03:08:54 +02:00
return
2024-06-02 22:17:15 +02:00
user = create_user(form.username.data, form.display_name.data, form.email.data)
if isinstance(user, Response):
return user
elif user is None:
return
2024-06-02 22:17:15 +02:00
user.password = make_flask_login_password(form.password.data)
2020-12-05 03:41:53 +01:00
2023-06-19 22:27:49 +02:00
add_audit_log(AuditSeverity.USER, user, "Registered with email, display name=" + user.display_name,
url_for("users.profile", username=user.username))
2023-06-19 22:27:49 +02:00
token = random_string(32)
ver = UserEmailVerification()
ver.user = user
ver.token = token
ver.email = form.email.data
db.session.add(ver)
db.session.commit()
2022-01-22 22:23:01 +01:00
send_verify_email.delay(form.email.data, token, get_locale().language)
return redirect(url_for("users.email_sent"))
@bp.route("/user/register/", methods=["GET", "POST"])
def register():
form = RegisterForm(request.form)
if form.validate_on_submit():
ret = handle_register(form)
if ret:
return ret
return render_template("users/register.html", form=form)
2020-12-05 01:18:00 +01:00
class ForgotPasswordForm(FlaskForm):
2022-01-07 22:55:33 +01:00
email = StringField(lazy_gettext("Email"), [InputRequired(), Email()])
submit = SubmitField(lazy_gettext("Reset Password"))
2020-12-04 23:29:10 +01:00
2023-06-19 20:32:36 +02:00
@bp.route("/user/forgot-password/", methods=["GET", "POST"])
def forgot_password():
2020-12-05 01:18:00 +01:00
form = ForgotPasswordForm(request.form)
2020-12-04 23:29:10 +01:00
if form.validate_on_submit():
2020-12-05 01:18:00 +01:00
email = form.email.data
user = User.query.filter_by(email=email).first()
if user:
2023-06-19 22:27:49 +02:00
token = random_string(32)
2020-12-05 01:18:00 +01:00
2023-06-19 22:27:49 +02:00
add_audit_log(AuditSeverity.USER, user, "(Anonymous) requested a password reset",
url_for("users.profile", username=user.username), None)
2020-12-05 03:41:53 +01:00
2020-12-05 01:18:00 +01:00
ver = UserEmailVerification()
ver.user = user
ver.token = token
ver.email = email
ver.is_password_reset = True
db.session.add(ver)
db.session.commit()
2020-12-04 23:29:10 +01:00
2022-01-22 22:23:01 +01:00
send_verify_email.delay(form.email.data, token, get_locale().language)
2020-12-05 01:18:00 +01:00
else:
2022-01-22 22:23:01 +01:00
html = render_template("emails/unable_to_find_account.html")
send_anon_email.delay(email, get_locale().language, gettext("Unable to find account"),
html, html)
2020-12-05 01:18:00 +01:00
return redirect(url_for("users.email_sent"))
2020-12-05 01:18:00 +01:00
return render_template("users/forgot_password.html", form=form)
class SetPasswordForm(FlaskForm):
2022-01-07 22:55:33 +01:00
email = StringField(lazy_gettext("Email"), [Optional(), Email()])
2023-08-26 15:54:58 +02:00
password = PasswordField(lazy_gettext("New password"), [InputRequired(), Length(12, 100)])
password2 = PasswordField(lazy_gettext("Verify password"), [InputRequired(), Length(12, 100),
2023-06-19 20:32:36 +02:00
EqualTo('password', message=lazy_gettext('Passwords must match'))])
2022-01-07 22:55:33 +01:00
submit = SubmitField(lazy_gettext("Save"))
2023-06-19 20:32:36 +02:00
2020-12-05 00:07:19 +01:00
class ChangePasswordForm(FlaskForm):
2023-08-26 15:54:58 +02:00
old_password = PasswordField(lazy_gettext("Old password"), [InputRequired(), Length(6, 100)])
password = PasswordField(lazy_gettext("New password"), [InputRequired(), Length(12, 100)])
password2 = PasswordField(lazy_gettext("Verify password"), [InputRequired(), Length(12, 100),
2022-01-07 22:55:33 +01:00
validators.EqualTo('password', message=lazy_gettext('Passwords must match'))])
submit = SubmitField(lazy_gettext("Save"))
2020-12-05 00:07:19 +01:00
def handle_set_password(form):
one = form.password.data
two = form.password2.data
if one != two:
2022-01-08 02:47:25 +01:00
flash(gettext("Passwords do not match"), "danger")
2020-12-05 00:07:19 +01:00
return
2023-06-19 22:27:49 +02:00
add_audit_log(AuditSeverity.USER, current_user, "Changed their password", url_for("users.profile", username=current_user.username))
2020-12-05 03:41:53 +01:00
2020-12-05 00:07:19 +01:00
current_user.password = make_flask_login_password(form.password.data)
if hasattr(form, "email"):
2023-06-19 22:27:49 +02:00
new_email = nonempty_or_none(form.email.data)
2023-06-19 20:32:36 +02:00
if new_email and new_email != current_user.email:
if EmailSubscription.query.filter_by(email=form.email.data, blacklisted=True).count() > 0:
2022-01-07 22:46:16 +01:00
flash(gettext(u"That email address has been unsubscribed/blacklisted, and cannot be used"), "danger")
return
user_by_email = User.query.filter_by(email=form.email.data).first()
if user_by_email:
2022-01-22 22:23:01 +01:00
send_anon_email.delay(form.email.data, get_locale().language, gettext("Email already in use"),
2022-01-07 22:46:16 +01:00
gettext(u"We were unable to create the account as the email is already in use by %(display_name)s. Try a different email address.",
display_name=user_by_email.display_name))
else:
2023-06-19 22:27:49 +02:00
token = random_string(32)
2020-12-05 00:07:19 +01:00
ver = UserEmailVerification()
ver.user = current_user
ver.token = token
2023-06-19 20:32:36 +02:00
ver.email = new_email
db.session.add(ver)
db.session.commit()
2022-01-22 22:23:01 +01:00
send_verify_email.delay(form.email.data, token, get_locale().language)
2022-01-07 22:46:16 +01:00
flash(gettext("Your password has been changed successfully."), "success")
return redirect(url_for("users.email_sent"))
2020-12-05 00:07:19 +01:00
db.session.commit()
2022-01-07 22:46:16 +01:00
flash(gettext("Your password has been changed successfully."), "success")
2020-12-05 00:07:19 +01:00
return redirect(url_for("homepage.home"))
@bp.route("/user/change-password/", methods=["GET", "POST"])
@login_required
def change_password():
2020-12-05 00:07:19 +01:00
form = ChangePasswordForm(request.form)
if form.validate_on_submit():
if check_password_hash(current_user.password, form.old_password.data):
ret = handle_set_password(form)
if ret:
return ret
else:
2022-01-07 22:46:16 +01:00
flash(gettext("Old password is incorrect"), "danger")
2020-12-05 00:07:19 +01:00
return render_template("users/change_set_password.html", form=form)
@bp.route("/user/set-password/", methods=["GET", "POST"])
@login_required
def set_password():
2020-12-04 23:35:22 +01:00
if current_user.password:
return redirect(url_for("users.change_password"))
form = SetPasswordForm(request.form)
if current_user.email is None:
form.email.validators = [InputRequired(), Email()]
2020-12-05 00:07:19 +01:00
if form.validate_on_submit():
ret = handle_set_password(form)
if ret:
return ret
return render_template("users/change_set_password.html", form=form)
2020-12-04 23:29:10 +01:00
@bp.route("/user/verify/")
def verify_email():
token = request.args.get("token")
ver: UserEmailVerification = UserEmailVerification.query.filter_by(token=token).first()
if ver is None:
2022-01-07 22:46:16 +01:00
flash(gettext("Unknown verification token!"), "danger")
return redirect(url_for("homepage.home"))
if ver.is_expired:
2022-01-07 22:46:16 +01:00
flash(gettext("Token has expired"), "danger")
db.session.delete(ver)
db.session.commit()
return redirect(url_for("homepage.home"))
user = ver.user
2023-06-19 22:27:49 +02:00
add_audit_log(AuditSeverity.USER, user, "Confirmed their email",
url_for("users.profile", username=user.username))
was_activating = not user.is_active
2020-12-05 22:30:36 +01:00
if ver.email and user.email != ver.email:
if User.query.filter_by(email=ver.email).count() > 0:
2022-01-07 22:46:16 +01:00
flash(gettext("Another user is already using that email"), "danger")
return redirect(url_for("homepage.home"))
2022-01-07 22:46:16 +01:00
flash(gettext("Confirmed email change"), "success")
2020-12-05 22:30:36 +01:00
if user.email:
send_user_email.delay(user.email,
2022-01-22 22:23:01 +01:00
user.locale or "en",
2022-01-07 22:46:16 +01:00
gettext("Email address changed"),
gettext("Your email address has changed. If you didn't request this, please contact an administrator."))
2020-12-05 22:30:36 +01:00
user.is_active = True
user.email = ver.email
2020-12-05 03:41:53 +01:00
db.session.delete(ver)
db.session.commit()
2020-12-05 01:18:00 +01:00
if ver.is_password_reset:
login_user(user)
user.password = None
2020-12-05 01:18:00 +01:00
db.session.commit()
return redirect(url_for("users.set_password"))
if current_user.is_authenticated:
return redirect(url_for("users.profile", username=current_user.username))
elif was_activating:
2022-01-07 22:46:16 +01:00
flash(gettext("You may now log in"), "success")
return redirect(url_for("users.login"))
else:
return redirect(url_for("homepage.home"))
2020-12-05 21:36:09 +01:00
class UnsubscribeForm(FlaskForm):
2022-01-07 22:55:33 +01:00
email = StringField(lazy_gettext("Email"), [InputRequired(), Email()])
submit = SubmitField(lazy_gettext("Send"))
2020-12-05 21:36:09 +01:00
def unsubscribe_verify():
form = UnsubscribeForm(request.form)
if form.validate_on_submit():
email = form.email.data
sub = EmailSubscription.query.filter_by(email=email).first()
if not sub:
sub = EmailSubscription(email)
db.session.add(sub)
2023-06-19 22:27:49 +02:00
sub.token = random_string(32)
2020-12-05 21:36:09 +01:00
db.session.commit()
2022-01-22 22:23:01 +01:00
send_unsubscribe_verify.delay(form.email.data, get_locale().language)
2020-12-05 21:36:09 +01:00
return redirect(url_for("users.email_sent"))
2020-12-05 21:36:09 +01:00
return render_template("users/unsubscribe.html", form=form)
def unsubscribe_manage(sub: EmailSubscription):
user = User.query.filter_by(email=sub.email).first()
if request.method == "POST":
2020-12-05 22:24:14 +01:00
if user:
user.email = None
2020-12-05 21:36:09 +01:00
sub.blacklisted = True
db.session.commit()
2022-01-07 22:46:16 +01:00
flash(gettext("That email is now blacklisted. Please contact an admin if you wish to undo this."), "success")
2020-12-05 21:36:09 +01:00
return redirect(url_for("homepage.home"))
return render_template("users/unsubscribe.html", user=user)
@bp.route("/unsubscribe/", methods=["GET", "POST"])
def unsubscribe():
token = request.args.get("token")
if token:
sub = EmailSubscription.query.filter_by(token=token).first()
if sub:
return unsubscribe_manage(sub)
return unsubscribe_verify()
@bp.route("/email_sent/")
def email_sent():
return render_template("users/email_sent.html")