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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
import functools
from flask import (
Blueprint,
flash,
g,
redirect,
render_template,
request,
session,
url_for,
Response,
)
from werkzeug.security import generate_password_hash, check_password_hash
from sw.db import get_db
bp = Blueprint("auth", __name__, url_prefix="/auth")
@bp.before_app_request
def load_logged_in_user():
user_id = session.get("user_id")
if user_id is None:
g.user = None
else:
g.user = (
get_db().execute("select * from user where id=?", (user_id,)).fetchone()
)
@bp.route("/register", methods=["POST"])
def register():
if not request.is_json:
return "Request body is not JSON", 422
data = request.json
if "username" not in data:
return "Username required", 400
if "password" not in data:
return "Password required", 400
username = data["username"]
password = data["password"]
if username is None:
return "Username required", 400
if password is None:
return "Password required", 400
if username == "":
return "Username must not be empty", 400
if password == "":
return "Password must not be empty", 400
db = get_db()
existing_user = db.execute(
"select id from user where username=?", (username,)
).fetchone()
if existing_user is not None:
return f"Username {username} is taken", 409
db.execute(
"insert into user (username, password) values (?, ?)",
(username, generate_password_hash(password)),
)
db.commit()
response = Response(status=201)
# response.location = url_for("ap.get_user", user=username)
return response
@bp.route("/login", methods=["POST"])
def login():
if not request.is_json:
return "Request body is not JSON", 422
username = request.json["username"]
password = request.json["password"]
db = get_db()
user = db.execute("select * from user where username=?", (username,)).fetchone()
if user is None:
return "Username or password incorrect", 403
if not check_password_hash(user["password"], password):
return "Username or password incorrect", 403
session.clear()
session["user_id"] = user["id"]
return 200
@bp.route("/logout")
def logout():
session.clear()
return 200
def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
return "Login required", 403
return view(**kwargs)
return wrapped_view
|