58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
from urllib.parse import urljoin, urlparse
|
|
from flask import Blueprint, flash, redirect, render_template, request, url_for
|
|
from flask_login import current_user, login_required, login_user, logout_user
|
|
from .models import User
|
|
|
|
auth = Blueprint("auth", __name__)
|
|
|
|
def is_safe_redirect_url(target: str | None) -> bool:
|
|
if not target:
|
|
return False
|
|
|
|
host_url = urlparse(request.host_url)
|
|
redirect_url = urlparse(urljoin(request.host_url, target))
|
|
|
|
return (
|
|
redirect_url.scheme in {"http", "https"}
|
|
and redirect_url.netloc == host_url.netloc
|
|
)
|
|
|
|
|
|
@auth.route("/login", methods=["GET", "POST"])
|
|
def login():
|
|
if current_user.is_authenticated:
|
|
return redirect(url_for("main.dashboard"))
|
|
|
|
if request.method == "GET":
|
|
return render_template("login.html")
|
|
|
|
email = request.form.get("email", "").strip().lower()
|
|
password = request.form.get("password", "")
|
|
remember = request.form.get("remember") == "on"
|
|
|
|
if not email or not password:
|
|
flash("Podaj adres e-mail i hasło.", "warning")
|
|
return render_template("login.html"), 400
|
|
|
|
user = User.query.filter_by(email=email).first()
|
|
|
|
if user is None or not user.check_password(password):
|
|
flash("Nieprawidłowy e-mail lub hasło.", "danger")
|
|
return render_template("login.html"), 401
|
|
|
|
login_user(user, remember=remember)
|
|
|
|
next_url = request.args.get("next")
|
|
|
|
if is_safe_redirect_url(next_url):
|
|
return redirect(next_url)
|
|
|
|
return redirect(url_for("main.dashboard"))
|
|
|
|
|
|
@auth.route("/logout", methods=["POST"])
|
|
@login_required
|
|
def logout():
|
|
logout_user()
|
|
flash("Zostałeś wylogowany.", "success")
|
|
return redirect(url_for("auth.login")) |