-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
243 lines (196 loc) · 6.95 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
from datetime import datetime
import flask_login
from bson import ObjectId
from db import db
from logger import logger
import json
import flask
from flask import Flask, render_template, send_from_directory
app = Flask(__name__)
app.secret_key = "PixelEconomy"
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
class User(flask_login.UserMixin):
pass
def check_credentials(username, password):
return db["users"].find_one({"username": username, "password": password})
@login_manager.user_loader
def user_loader(username):
user = User()
user.id = username
return user
@login_manager.request_loader
def request_loader(request):
username = request.form.get('username')
if check_credentials(request.form.get('username'), request.form.get('password')):
user = User()
user.id = username
user.is_authenticated = True
return user
@app.route('/login', methods=['GET', 'POST'])
def login():
if flask.request.method == 'GET':
return render_template("pages/login.html", title="Login", nosidebar=True)
username = flask.request.form['username']
password = flask.request.form['password']
if check_credentials(username, password):
user = User()
user.id = username
flask_login.login_user(user)
return flask.redirect(flask.url_for("index"))
return render_template("msg-redir.html", nosidebar=True, content="Bad login")
@app.route('/protected')
@flask_login.login_required
def protected():
return 'Logged in as: ' + flask_login.current_user.id
@app.route('/logout')
def logout():
flask_login.logout_user()
return render_template("msg-redir.html", nosidebar=True, content="Logged out")
@app.context_processor
def inject_site_data():
return {
"site": {
"title": "PixelEconomy",
"tagline": "Virtual marketplace for pixel art",
# "url": "",
"version": "0.1.0",
# "google_analytics_id": "",
"year": datetime.now().year,
}
}
@app.context_processor
def inject_user_data():
try:
user_data = db["users"].find_one({"username": flask_login.current_user.id})
return {
"user": {
"username": user_data["username"],
"balance": user_data["balance"],
}
}
except:
return {
"user": {
"username": "invalid",
"balance": -1,
}
}
@app.route('/res/<path:path>')
def send_res(path):
return send_from_directory('res', path)
@app.route('/marketplace')
@flask_login.login_required
def marketplace():
arts = []
# get arts from database
for market_entry in db["market"].find():
art_id = market_entry["art"]
data_art = db["art"].find_one({"_id": art_id})
creator_username = db["users"].find_one({"_id": data_art["creator"]})["username"]
arts.append({
"title": data_art["title"],
"creator": creator_username,
"price": market_entry["price"],
"data": data_art["data"],
"id": market_entry["_id"],
})
return render_template(r"pages/marketplace.html", title="Marketplace", arts=arts)
@app.route('/my-portfolio')
@flask_login.login_required
def my_portfolio():
arts = []
# get arts from database
try:
user_data = db["users"].find_one({"username": flask_login.current_user.id})
for art_id in user_data["portfolio"]:
data_art = db["art"].find_one({"_id": art_id})
creator_username = db["users"].find_one({"_id": data_art["creator"]})["username"]
arts.append({
"title": data_art["title"],
"creator": creator_username,
"data": data_art["data"],
"id": art_id,
"on_marketplace": db["market"].find_one({"art": data_art["_id"]}) is not None,
})
except:
pass
return render_template(r"pages/my-portfolio.html", title="My Portfolio", arts=arts)
@app.route('/create')
@flask_login.login_required
def create():
return render_template(r"pages/create.html", title="Create")
@app.route("/about")
@flask_login.login_required
def about():
return render_template(r"pages/about.html", title="About")
@app.route("/")
def index():
logged_in = False
try:
logger.debug("Logged in visit to index: {}".format(flask_login.current_user.id))
logged_in = True
except:
pass
if logged_in:
return flask.redirect(flask.url_for("marketplace"))
else:
return flask.redirect(flask.url_for("login"))
@app.route("/api/save", methods=['POST'])
@flask_login.login_required
def api_save():
body = json.loads(flask.request.data.decode('utf8'))
try:
user_data = db["users"].find_one({"username": flask_login.current_user.id})
art_id = db["art"].insert_one({
"title": body["title"],
"creator": user_data["_id"],
"data": body["data"]
}).inserted_id
db["users"].update_one({"_id": user_data["_id"]}, {"$push": {"portfolio": art_id}})
except:
pass
return ""
@app.route("/api/sell", methods=['POST'])
@flask_login.login_required
def api_sell():
body = json.loads(flask.request.data.decode('utf8'))
try:
art_data = db["art"].find_one({"_id": ObjectId(body["art_id"])})
db["market"].insert_one({
"art": art_data["_id"],
"price": body["price"],
})
except:
pass
return ""
@app.route("/api/buy", methods=['POST'])
@flask_login.login_required
def api_buy():
body = json.loads(flask.request.data.decode('utf8'))
try:
# gather market data
market_id = body["market_id"]
market_data = db["market"].find_one({"_id": ObjectId(market_id)})
# get user data
user = db["users"].find_one({"username": flask_login.current_user.id})
# get owner of art
owner = db["users"].find_one({"portfolio": market_data["art"]})
# remove art from its (previous) owner's portfolio
db["users"].update_one({"_id": owner["_id"]}, {"$pull": {"portfolio": market_data["art"]}})
# add art to new owner's portfolio (the user's)
db["users"].update_one({"_id": user["_id"]}, {"$push": {"portfolio": market_data["art"]}})
# subtract price from user's balance
price = market_data["price"]
original_balance = db["users"].find_one({"_id": user["_id"]})["balance"]
db["users"].update_one({"_id": user["_id"]}, {"$set": {"balance": original_balance - price}})
# add price to original owner's balance
original_balance = db["users"].find_one({"_id": owner["_id"]})["balance"]
db["users"].update_one({"_id": owner["_id"]}, {"$set": {"balance": original_balance + price}})
# remove art from marketplace
db["market"].remove({"_id": ObjectId(market_id)})
except:
pass
return ""
if __name__ == '__main__':
app.run()