1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
# -*- coding: utf-8 -*-
from flask import Blueprint
from flask import redirect, request, flash, render_template, url_for
from flask_login import login_user, logout_user, current_user
from urllib.parse import urljoin, urlparse
from werkzeug import Response
from accounts.app import accounts_app
from typing import Union
from .forms import LoginForm
bp = Blueprint("login", __name__)
def is_safe_url(target: str):
ref_url = urlparse(request.host_url)
test_url = urlparse(urljoin(request.host_url, target))
print(target)
print(test_url)
return (
test_url.scheme in ("http", "https")
and ref_url.netloc == test_url.netloc
and test_url.path == target
)
@bp.route("/login", methods=["GET", "POST"])
def login() -> Union[str, Response]:
if current_user.is_authenticated:
return redirect(url_for("default.index"))
form = LoginForm(request.form)
if form.validate_on_submit():
try:
user = accounts_app.user_backend.auth(
form.username.data, form.password.data
)
login_user(user)
flash("Erfolgreich eingeloggt", "success")
next = request.form["next"]
return redirect(
next if is_safe_url(next) else url_for("default.index")
)
except (
accounts_app.user_backend.NoSuchUserError,
accounts_app.user_backend.InvalidPasswordError,
):
flash("Ungültiger Benutzername und/oder Passwort", "error")
return render_template(
"login/login.html", form=form, next=request.values.get("next")
)
@bp.route("/logout")
def logout() -> Response:
logout_user()
flash("Erfolgreich ausgeloggt.", "success")
return redirect(url_for(".login"))
|