-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
119 lines (91 loc) · 2.47 KB
/
app.py
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
from flask import Flask, Response, abort, redirect, render_template, request, url_for
from flask_login import (
LoginManager,
UserMixin,
current_user,
login_required,
login_user,
logout_user,
)
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.config.update(
DEBUG=True,
SECRET_KEY="secret_sauce",
)
login_manager = LoginManager()
login_manager.init_app(app)
csrf = CSRFProtect()
csrf.init_app(app)
# database
users = [
{
"id": 1,
"username": "test",
"password": "test",
"balance": 2000,
},
{
"id": 2,
"username": "hacker",
"password": "hacker",
"balance": 0,
},
]
class User(UserMixin):
...
def get_user(user_id: int):
for user in users:
if int(user["id"]) == int(user_id):
return user
return None
@login_manager.user_loader
def user_loader(id: int):
user = get_user(id)
if user:
user_model = User()
user_model.id = user["id"]
return user_model
return None
@app.errorhandler(401)
def unauthorized(error):
return Response("Not authorized"), 401
@app.route("/", methods=["GET", "POST"])
def homepage():
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
for user in users:
if user["username"] == username and user["password"] == password:
user_model = User()
user_model.id = user["id"]
login_user(user_model)
return redirect(url_for("accounts"))
else:
return abort(401)
if current_user.is_authenticated:
return redirect(url_for("accounts"))
return render_template("index.html")
@app.route("/accounts", methods=["GET", "POST"])
@login_required
def accounts():
user = get_user(current_user.id)
if request.method == "POST":
amount = int(request.form.get("amount"))
account = int(request.form.get("account"))
transfer_to = get_user(account)
if amount <= user["balance"] and transfer_to:
user["balance"] -= amount
transfer_to["balance"] += amount
return render_template(
"accounts.html",
balance=user["balance"],
username=user["username"],
)
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("homepage"))
if __name__ == "__main__":
app.run(debug=True)