app-MAIL-temp/app/auth/views/recovery.py

76 lines
2.5 KiB
Python
Raw Normal View History

2020-05-17 10:13:04 +02:00
import arrow
from flask import request, render_template, redirect, url_for, flash, session, g
2020-05-17 10:13:04 +02:00
from flask_login import login_user
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from app.auth.base import auth_bp
from app.config import MFA_USER_ID
from app.db import Session
from app.email_utils import send_invalid_totp_login_email
from app.extensions import limiter
2020-05-17 10:13:04 +02:00
from app.log import LOG
from app.models import User, RecoveryCode
2022-03-29 18:03:18 +02:00
from app.utils import sanitize_next_url
2020-05-17 10:13:04 +02:00
class RecoveryForm(FlaskForm):
code = StringField("Code", validators=[validators.DataRequired()])
@auth_bp.route("/recovery", methods=["GET", "POST"])
@limiter.limit(
"10/minute", deduct_when=lambda r: hasattr(g, "deduct_limit") and g.deduct_limit
)
2020-05-17 10:13:04 +02:00
def recovery_route():
# passed from login page
user_id = session.get(MFA_USER_ID)
# user access this page directly without passing by login page
if not user_id:
flash("Unknown error, redirect back to main page", "warning")
return redirect(url_for("auth.login"))
user = User.get(user_id)
if not user.two_factor_authentication_enabled():
flash("Only user with MFA enabled should go to this page", "warning")
return redirect(url_for("auth.login"))
recovery_form = RecoveryForm()
2022-03-29 18:03:18 +02:00
next_url = sanitize_next_url(request.args.get("next"))
2020-05-17 10:13:04 +02:00
if recovery_form.validate_on_submit():
code = recovery_form.code.data
recovery_code = RecoveryCode.find_by_user_code(user, code)
2020-05-17 10:13:04 +02:00
if recovery_code:
if recovery_code.used:
# Trigger rate limiter
g.deduct_limit = True
2020-05-17 10:13:04 +02:00
flash("Code already used", "error")
else:
del session[MFA_USER_ID]
login_user(user)
flash("Welcome back!", "success")
2020-05-17 10:13:04 +02:00
recovery_code.used = True
recovery_code.used_at = arrow.now()
Session.commit()
2020-05-17 10:13:04 +02:00
# User comes to login page from another page
if next_url:
2021-09-08 11:29:55 +02:00
LOG.d("redirect user to %s", next_url)
2020-05-17 10:13:04 +02:00
return redirect(next_url)
else:
2021-09-08 11:29:55 +02:00
LOG.d("redirect user to dashboard")
2020-05-17 10:13:04 +02:00
return redirect(url_for("dashboard.index"))
else:
# Trigger rate limiter
g.deduct_limit = True
2022-01-20 17:44:15 +01:00
flash("Incorrect code", "error")
send_invalid_totp_login_email(user, "recovery")
2020-05-17 10:13:04 +02:00
return render_template("auth/recovery.html", recovery_form=recovery_form)