capsul-flask/capsulflask/auth.py

67 lines
1.8 KiB
Python
Raw Normal View History

2020-05-10 01:36:14 +00:00
import functools
from flask import Blueprint
2020-05-10 03:59:22 +00:00
from flask import flash
from flask import current_app
2020-05-10 01:36:14 +00:00
from flask import g
from flask import redirect
from flask import url_for
2020-05-10 03:59:22 +00:00
from flask import request
2020-05-10 01:36:14 +00:00
from flask import session
2020-05-10 03:59:22 +00:00
from flask import render_template
from flask_mail import Message
2020-05-10 01:36:14 +00:00
from capsulflask.db import get_model
bp = Blueprint("auth", __name__, url_prefix="/auth")
def account_required(view):
"""View decorator that redirects anonymous users to the login page."""
@functools.wraps(view)
def wrapped_view(**kwargs):
if session.get("account") is None:
return redirect(url_for("auth.login"))
return view(**kwargs)
return wrapped_view
2020-05-10 03:59:22 +00:00
@bp.route("/login", methods=("GET", "POST"))
def login():
2020-05-10 01:36:14 +00:00
if request.method == "POST":
email = request.form["email"]
error = None
if not email:
error = "Email is required."
if error is None:
2020-05-10 03:59:22 +00:00
token = get_model().login(email)
link = f"{current_app.config['BASE_URL']}/auth/magic/{token}"
current_app.config["FLASK_MAIL_INSTANCE"].send(
Message(
"Click This Link to Login to Capsul",
body=f"""
Navigate to {link} to log into capsul.
""",
html=f"""
Navigate to <a href="{link}">{link}</a> to log into capsul.
""",
sender=current_app.config['MAIL_DEFAULT_SENDER'],
recipients=[email]
)
2020-05-10 01:36:14 +00:00
)
2020-05-10 03:59:22 +00:00
return render_template("check-your-email.html")
2020-05-10 01:36:14 +00:00
flash(error)
2020-05-10 03:59:22 +00:00
return render_template("login.html")
@bp.route("/logout")
def logout():
session.clear()
return redirect(url_for("index"))