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

65 lines
1.9 KiB
Python
Raw Normal View History

2020-04-09 22:22:26 +02:00
from typing import Optional
from flask import session, redirect, url_for, request
from flask_login import login_user
from app.config import MFA_USER_ID
from app.log import LOG
2020-04-09 22:22:26 +02:00
from app.models import Referral
def after_login(user, next_url):
"""
Redirect to the correct page after login.
If user enables MFA: redirect user to MFA page
Otherwise redirect to dashboard page if no next_url
"""
2020-05-07 14:32:52 +02:00
if user.fido_enabled():
2020-05-05 12:16:52 +02:00
# Use the same session for FIDO so that we can easily
# switch between these two 2FA option
session[MFA_USER_ID] = user.id
if next_url:
2020-05-17 10:28:00 +02:00
return redirect(url_for("auth.fido", next=next_url))
2020-05-05 12:16:52 +02:00
else:
2020-05-07 11:53:28 +02:00
return redirect(url_for("auth.fido"))
2020-05-05 12:16:52 +02:00
elif user.enable_otp:
session[MFA_USER_ID] = user.id
if next_url:
2020-05-17 10:28:00 +02:00
return redirect(url_for("auth.mfa", next=next_url))
else:
return redirect(url_for("auth.mfa"))
else:
2021-09-08 11:29:55 +02:00
LOG.d("log user %s in", user)
login_user(user)
# 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)
return redirect(next_url)
else:
2021-09-08 11:29:55 +02:00
LOG.d("redirect user to dashboard")
return redirect(url_for("dashboard.index"))
2020-04-09 22:22:26 +02:00
# name of the cookie that stores the referral code
_REFERRAL_COOKIE = "slref"
def get_referral() -> Optional[Referral]:
"""Get the eventual referral stored in cookie"""
# whether user arrives via a referral
referral = None
if request.cookies:
ref_code = request.cookies.get(_REFERRAL_COOKIE)
referral = Referral.get_by(code=ref_code)
if not referral:
if "slref" in session:
ref_code = session["slref"]
referral = Referral.get_by(code=ref_code)
if referral:
LOG.d("referral found %s", referral)
2020-04-09 22:22:26 +02:00
return referral