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, User 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("/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(): conn = glob.get_sql_connection() cur = conn.cursor() cur.execute(""" SELECT BrukerID FROM Bruker WHERE Epost = %s AND Passord = %s LIMIT 1; """, (form.email.data, form.password.data)) uuid = cur.fetchone() cur.close() if uuid is None: flash("Invalid login", "danger") return render_template("login.html", form=form) user = User(int(uuid[0])) 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("/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): return User(uuid) @login_manager.unauthorized_handler def unauthorized_handler(): return redirect(url_for("login"))