split api pythons
This commit is contained in:
+49
-10
@@ -1,19 +1,58 @@
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, flash
|
||||
from flask_login import login_user, logout_user, login_required
|
||||
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 request.method == "POST":
|
||||
user = User.query.filter_by(email=request.form["email"].strip().lower()).first()
|
||||
if user and user.check_password(request.form["password"]):
|
||||
login_user(user); return redirect(url_for("main.dashboard"))
|
||||
flash("Nieprawidłowy e-mail lub hasło", "danger")
|
||||
return render_template("login.html")
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for("main.dashboard"))
|
||||
|
||||
@auth.route("/logout")
|
||||
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(); return redirect(url_for("auth.login"))
|
||||
logout_user()
|
||||
flash("Zostałeś wylogowany.", "success")
|
||||
return redirect(url_for("auth.login"))
|
||||
Reference in New Issue
Block a user