Extract login utils out of two_factor view

This better reflects how the code is reused in other views and is
not specific to two factor actions. We have a pattern of testing
utility functionality for each view (as opposed to testing the util
+ the view calls the util), so I'm leaving the tests as-is.
This commit is contained in:
Ben Thorner
2021-06-14 11:15:57 +01:00
parent 3250f2b3ed
commit bf2e6802bf
4 changed files with 45 additions and 40 deletions

View File

@@ -17,7 +17,11 @@ from app.main import main
from app.main.forms import TwoFactorForm
from app.models.user import User
from app.utils import is_less_than_days_ago
from app.utils.login import redirect_to_sign_in
from app.utils.login import (
log_in_user,
redirect_to_sign_in,
redirect_when_logged_in,
)
@main.route('/two-factor-email-sent', methods=['GET'])
@@ -97,38 +101,3 @@ def revalidate_email_sent():
title = 'Email resent' if request.args.get('email_resent') else 'Check your email'
redirect_url = request.args.get('next')
return render_template('views/re-validate-email-sent.html', title=title, redirect_url=redirect_url)
# see http://flask.pocoo.org/snippets/62/
def _is_safe_redirect_url(target):
from urllib.parse import urljoin, urlparse
host_url = urlparse(request.host_url)
redirect_url = urlparse(urljoin(request.host_url, target))
return redirect_url.scheme in ('http', 'https') and \
host_url.netloc == redirect_url.netloc
def log_in_user(user_id):
try:
user = User.from_id(user_id)
# the user will have a new current_session_id set by the API - store it in the cookie for future requests
session['current_session_id'] = user.current_session_id
# Check if coming from new password page
if 'password' in session.get('user_details', {}):
user.update_password(session['user_details']['password'], validated_email_access=True)
user.activate()
user.login()
finally:
# get rid of anything in the session that we don't expect to have been set during register/sign in flow
session.pop("user_details", None)
session.pop("file_uploads", None)
return redirect_when_logged_in(platform_admin=user.platform_admin)
def redirect_when_logged_in(platform_admin):
next_url = request.args.get('next')
if next_url and _is_safe_redirect_url(next_url):
return redirect(next_url)
return redirect(url_for('main.show_accounts_or_dashboard'))