from flask import render_template, url_for, request, redirect, flash, abort from wtforms import Form, BooleanField, StringField, PasswordField, validators import flask_login from forms.login import LoginForm, RegisterForm, User, register_account from objects import glob # Global sharing of python objects in a manageable way login_manager = flask_login.LoginManager() login_manager.init_app(glob.app) login_manager.login_view = "login" logged_in_users = [] @glob.app.route("/") @glob.app.route("/home") @glob.app.route("/dashboard") @flask_login.login_required def dashboard(): return render_template("pages/dashboard.html") @glob.app.route("/bills") @flask_login.login_required def bills(): conn = glob.make_sql_connection() cur = conn.cursor() cur.execute(""" SELECT Betaletil, Regningfor, Regningsum, KID, Betalingsfrist, Betalt FROM Regninger WHERE BrukerID = %s """, (flask_login.current_user.id,)) data = [] for row in cur: data.append(row) cur.close() conn.close() return render_template("pages/bills.html", data=data) @glob.app.route("/warranties") @flask_login.login_required def warranties(): return "AAAA" @glob.app.route("/receipts") @flask_login.login_required def receipts(): return "AAAA" @glob.app.route("/login", methods = ["GET", "POST"]) def login(): if flask_login.current_user.is_authenticated: flash("Already logged in", "info") return redirect(url_for("dashboard")) form = LoginForm(request.form) if request.method == "POST" and form.validate(): try: user = User((form.email.data, form.password.data)) except Exception as e: flash(str(e), "danger") return render_template("login.html", form=form) flask_login.login_user(user) logged_in_users.append(user) flash("Logged in", "success") return redirect(url_for("dashboard")) return render_template("login.html", form=form) @glob.app.route("/register", methods = ["GET", "POST"]) def register(): if flask_login.current_user.is_authenticated: flash("Already logged in", "info") return redirect(url_for("dashboard")) form = RegisterForm(request.form) if request.method == "POST" and form.validate(): try: register_account(form.email.data, form.password.data, form.firstname.data, form.surname.data) except Exception as e: flash(str(e), "danger") return render_template("register.html", form=form) flash("User registered", "success") return redirect(url_for("login")) return render_template("register.html", form=form) @glob.app.route("/logout") @flask_login.login_required def logout(): flask_login.logout_user() flash("Logged out", "success") return redirect(url_for("login")) @glob.app.errorhandler(401) def unauthorized_handler_err(): flash("Login is required", "danger") unauthorized_handler() @login_manager.user_loader def load_user(uuid): uuid = int(uuid) lst = [x for x in logged_in_users if x.id == uuid] return lst[0] if len(lst) > 0 else None @login_manager.unauthorized_handler def unauthorized_handler(): return redirect(url_for("login"))