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
65
66
67
68
69
70
71
72
73
|
# -*- mode: python; -*-
from flask import Blueprint, render_template, redirect, url_for, request, flash
from flask_login import login_user, login_required, logout_user
from werkzeug.security import generate_password_hash, check_password_hash
from ... import db
from ...models import User
from .forms import LoginForm, RegisterForm
auth = Blueprint("auth", __name__)
@auth.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
req = request.form
# print(req["remember"])
remember = True if req.get("remember") else False
user = User.query.filter_by(username=req["username"]).first()
if user is None:
flash("User not registered.", "error")
return redirect(url_for("auth.register"))
if check_password_hash(user.hashed_password, req["password"]) is False:
flash("Wrong password.", "error")
return redirect(url_for("auth.login"))
login_user(user, remember=remember)
flash(
f"Logged in as user {user.username} successfully. "
+ f"You will {'not' if remember is False else ''} be remembered next time!"
)
return redirect(url_for("main.home"))
return render_template("modules/login.html", form=form)
@auth.route("/register", methods=["GET", "POST"])
def register():
form = RegisterForm()
if form.validate_on_submit():
req = request.form
user_already_exists = User.query.filter_by(
name_first=req["name_first"],
name_last=req["name_last"],
).first()
if user_already_exists:
flash(
f"User {req['name_first']} {req['name_last']} already exists.", "error"
)
return redirect(url_for("auth.login"))
new_user = User(
username=req["username"],
hashed_password=generate_password_hash(req["password"], method="sha256"),
name_first=req["name_first"],
name_last=req["name_last"],
email=req["email"],
phone_mobile=req["phone_mobile"],
phone_alternative=req["phone_alternative"],
)
db.session.add(new_user)
db.session.commit()
flash(f"Created user {req['name_first']} {req['name_last']} successfully.")
return redirect(url_for("main.home"))
return render_template("register.html", form=form)
@auth.route("/logout")
@login_required
def logout():
logout_user()
flash(f"Logged out successfully.")
return redirect(url_for("main.home"))
|