forked from Tapin42/cfbr_orders
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflask_app.py
405 lines (337 loc) · 15.3 KB
/
flask_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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
from flask import Flask, abort, request, make_response, redirect, render_template
import requests
import requests.auth
from uuid import uuid4
import urllib
from datetime import datetime, timedelta
from pytz import timezone
from constants import *
from cfbr_db import Db
from orders import Orders
from admin_page import Admin
from logger import Logger
Logger.init_logging()
log = Logger.getLogger(__name__)
app = Flask(__name__)
###############################################################
#
# Functions to handle routes & Flask app logic
#
###############################################################
CONFIRMATION_PAGE = "confirmation.html"
ORDER_PAGE = "order.html"
ERROR_PAGE = "error.html"
REDDIT_SITE = 'reddit'
DISCORD_SITE = 'discord'
@app.route('/')
def homepage():
if POSTGAME:
if POSTGAME == "Yay!":
return make_response(render_template('postgame-yay.html'))
elif POSTGAME == "Boo!":
return make_response(render_template('postgame-boo.html'))
cookie = request.cookies.get('access-token')
auth_resp_if_necessary, username = check_identity_or_auth(request)
# The user needs to authenticate, short-circuit here.
if auth_resp_if_necessary:
return auth_resp_if_necessary
template_params = {"username": username}
cfbr_api_user_response = requests.get(f"{CFBR_REST_API}/player?player={username}")
try:
cfbr_api_user_response.raise_for_status()
except requests.exceptions.HTTPError or AttributeError as e:
log.error(f"{username}: Reddit user who doesn't play CFBR tried to log in")
log.error(f"Exception: {e}")
template_params |= {
"error_message": f"Sorry, you'll need to sign up for CFB Risk and join {THE_GOOD_GUYS} first.",
"link": "https://collegefootballrisk.com/"
}
return build_template_response(cookie, ERROR_PAGE, template_params)
active_team = cfbr_api_user_response.json()['active_team']['name']
current_stars = cfbr_api_user_response.json()['ratings']['overall']
template_params |= {
"is_admin": Admin.is_admin(username),
"current_stars": current_stars,
"hoy": what_day_is_it(),
"confirm_url": CONFIRM_URL
}
# Enemy rogue or SPY!!!! Just give them someone to attack.
if active_team != THE_GOOD_GUYS:
# TODO: This codepath is currently broken. Don't rely on it until it gets fixed again.
# order = Orders.get_foreign_order(active_team, CFBR_day(), CFBR_month())
log.info(f"{username}: Player on {active_team} tried to log in.")
template_params |= {"error_message": f"Sorry, you'll need to join {THE_GOOD_GUYS} first."}
return build_template_response(cookie, ERROR_PAGE, template_params)
# Good guys get their assignments here
else:
# We now have three states, ordered in reverse chronological:
# 3) The user has already accepted an order. Show them the thank-you screen, but remind them what (we think)
# they did
# 2) The user has been offered a few options. Retrieve those options and then display them (or confirm
# their choice)
# 1) The user is showing up for the first time. Create offers for them and display them.
# (...and 0) There aren't any plans available yet to pick from.
# Stage 3: This user has already been here and done that.
existing_move = Orders.user_already_moved(username, CFBR_day(), CFBR_month())
if existing_move is not None:
log.info(f"{username}: Showing them the move they previously made.")
template_params |= {"territory": existing_move}
return build_template_response(cookie, CONFIRMATION_PAGE, template_params)
# They're not in Stage 3. Are they in stage 2, or did they make a choice?
confirmed_territory = None
confirmation = request.args.get('confirmed', default=None, type=str)
if confirmation:
confirmed_territory = Orders.confirm_offer(username, CFBR_day(), CFBR_month(), confirmation)
if confirmed_territory:
# They made a choice! Our favorite.
log.info(f"{username}: Chose to move on {confirmed_territory}")
template_params |= {"territory": confirmed_territory}
return build_template_response(cookie, CONFIRMATION_PAGE, template_params)
else:
existing_offers = Orders.user_already_offered(username, CFBR_day(), CFBR_month())
if existing_offers is not None and len(existing_offers) > 0:
log.info(f"{username}: Showing them their previous offers.")
template_params |= {"orders": existing_offers}
return build_template_response(cookie, ORDER_PAGE, template_params)
# I guess they're in Stage 1: Make them an offer
new_offer_territories = Orders.get_next_offers(CFBR_day(), CFBR_month(), current_stars)
if len(new_offer_territories) > 0:
new_offers = []
for i in range(len(new_offer_territories)):
offer_uuid = Orders.write_new_offer(username, new_offer_territories[i],
CFBR_day(), CFBR_month(), current_stars, i)
new_offers.append((new_offer_territories[i], offer_uuid))
log.info(f"{username}: Generated new offers.")
template_params |= {"orders": new_offers}
return build_template_response(cookie, ORDER_PAGE, template_params)
else:
log.info(f"{username}: Tried to generate new offers and failed. Are the plans loaded for today?")
# Nope sorry we're in stage 0: Ain't no orders available yet. We'll use the order template
# sans orders until we create a page with a sick meme telling the Strategists to hurry up.
log.warning(f"{username}: Hit the 'No Orders Loaded' page")
return build_template_response(cookie, ORDER_PAGE, template_params)
def build_template_response(cookie, template, template_params):
resp = make_response(render_template(template, **template_params))
if cookie:
resp.set_cookie('access-token', cookie)
return resp
@app.route(REDDIT_CALLBACK_ROUTE)
def reddit_callback():
error = request.args.get('error', '')
if error:
template_params = {
"error_message": f"There was an error with reddit authentication. Please contact the website devs below.",
"link": GOOD_GUYS_DISCORD_LINK
}
return build_template_response(None, ERROR_PAGE, template_params)
state = request.args.get('state', '')
if not is_valid_state(state):
# Uh-oh, this request wasn't started by us!
log.error(f"unknown,403 from Reddit Auth API. WTF bro.")
abort(403)
code = request.args.get('code')
access_token = get_token(code)
if access_token:
response = make_response(redirect('/'))
response.set_cookie('access-token', access_token.encode())
response.set_cookie('auth-site',REDDIT_SITE)
return response
template_params = {
"error_message": f"Sorry, there was a problem authenticating you. Please contact the devs on Discord.",
"link": GOOD_GUYS_DISCORD_LINK
}
return build_template_response(None, ERROR_PAGE, template_params)
@app.route(DISCORD_CALLBACK_ROUTE)
def discord_callback():
error = request.args.get('error', '')
template_params = {
"error_message": f"There was an error with discord authentication. Please contact the website devs below.",
"link": GOOD_GUYS_DISCORD_LINK
}
if error:
return build_template_response(None, ERROR_PAGE, template_params)
state = request.args.get('state', '')
if not is_valid_state(state):
# Uh-oh, this request wasn't started by us!
log.error(f"unknown,403 from Discord Auth API. WTF bro.")
abort(403)
code = request.args.get('code')
access_token = get_discord_token(code)
if access_token:
response = make_response(redirect('/'))
response.set_cookie('access-token', access_token.encode())
response.set_cookie('auth-site', DISCORD_SITE)
return response
template_params = {
"error_message": f"Sorry, there was a problem authenticating you. Please contact the devs on Discord.",
"link": GOOD_GUYS_DISCORD_LINK
}
return build_template_response(None, ERROR_PAGE, template_params)
@app.route('/admin')
def admin_page():
auth_resp_if_necessary, username = check_identity_or_auth(request)
# The user needs to authenticate, short-circuit here.
if auth_resp_if_necessary:
return auth_resp_if_necessary
return Admin.build_page(request, username, CFBR_day(), CFBR_month())
@app.route('/admin/territories')
def admin_territory_page():
auth_resp_if_necessary, username = check_identity_or_auth(request)
# The user needs to authenticate, short-circuit here.
if auth_resp_if_necessary:
return auth_resp_if_necessary
return Admin.build_territory_page(request, username, CFBR_day(), CFBR_month())
@app.teardown_appcontext
def close_connection(exception):
Db.close_connection(exception)
###############################################################
#
# Functions to handle time
#
###############################################################
def CFBR_month():
tz = timezone('EST')
today = datetime.now(tz)
hour = int(today.strftime("%H"))
minute = int(today.strftime("%M"))
if (hour == 23) or ((hour == 22) and (minute > 29)):
today = datetime.now(tz) + timedelta(days=1)
if today.strftime("%A") == "Sunday":
today = today + timedelta(days=1)
return today.strftime("%-m")
def CFBR_day():
tz = timezone('EST')
today = datetime.now(tz)
hour = int(today.strftime("%H"))
minute = int(today.strftime("%M"))
if (hour == 23) or ((hour == 22) and (minute > 29)):
today = datetime.now(tz) + timedelta(days=1)
if today.strftime("%A") == "Sunday":
today = today + timedelta(days=1)
return today.strftime("%-d")
# Pretty date, for the user so not CFBR
def what_day_is_it():
tz = timezone('EST')
return datetime.now(tz).strftime("%B %d, %Y")
###############################################################
#
# Boilerplate for any page loads
#
###############################################################
def check_identity_or_auth(request):
access_token = request.cookies.get('access-token')
auth_site = request.cookies.get('auth-site')
if access_token is None:
log.debug(f"Incoming request with no access token, telling them to auth the app")
reddit_link = make_reddit_authorization_url()
discord_link = make_discord_authorization_url()
resp = make_response(render_template('auth.html', redditauthlink=reddit_link, discordauthlink=discord_link))
return (resp, None)
if auth_site == REDDIT_SITE:
headers = {"Authorization": "bearer " + access_token, 'User-agent': 'CFB Risk Orders'}
response = requests.get(REDDIT_ACCOUNT_URI, headers=headers)
elif auth_site == DISCORD_SITE:
headers = {"Authorization": "Bearer " + access_token, 'User-agent': 'CFB Risk Orders'}
response = requests.get(DISCORD_ACCOUNT_URI, headers=headers)
if response.status_code == 401:
log.error(f"{access_token},401 Error from CFBR API")
reddit_link = make_reddit_authorization_url()
discord_link = make_discord_authorization_url()
resp = make_response(render_template('auth.html', redditauthlink=reddit_link, discordauthlink=discord_link))
return (resp, None)
# If we made it this far, we theoretically know the user's identity. Say so.
if auth_site == REDDIT_SITE:
username = get_username(access_token)
elif auth_site == DISCORD_SITE:
# We add the $0 because that's what Mau is doing with discord verification right now.
# He wants to make it user ID eventually
username = get_discord_username(access_token)+"$0"
return (None, username)
###############################################################
#
# Discord API helper functions
#
###############################################################
def make_discord_authorization_url():
params = {"client_id": DISCORD_CLIENT_ID,
"response_type": "code",
"redirect_uri": DISCORD_REDIRECT_URI,
"scope": "identify"}
url = f"{DISCORD_AUTH_URI}?{urllib.parse.urlencode(params)}"
return url
def get_discord_token(code):
client_auth = requests.auth.HTTPBasicAuth(DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET)
post_data = {"grant_type": "authorization_code",
"code": code,
"redirect_uri": DISCORD_REDIRECT_URI}
response = requests.post(DISCORD_TOKEN_URI,
auth=client_auth,
headers={'User-agent': 'CFB Risk Orders'},
data=post_data)
token_json = response.json()
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
log.error(f"Failed to get Discord access token.")
log.error(f"{token_json=}")
log.error(f"Exception: {e}")
return
return token_json['access_token']
def get_discord_username(access_token):
headers = {"Authorization": "Bearer " + access_token, 'User-agent': 'CFB Risk Orders'}
response = requests.get(DISCORD_ACCOUNT_URI, headers=headers)
me_json = response.json()
return me_json['username']
###############################################################
#
# Reddit API helper functions
#
###############################################################
def make_reddit_authorization_url():
state = str(uuid4())
save_created_state(state)
params = {"client_id": REDDIT_CLIENT_ID,
"response_type": "code",
"state": state,
"redirect_uri": REDIRECT_URI,
"duration": "temporary",
"scope": "identity"}
url = f"{REDDIT_AUTH_URI}?{urllib.parse.urlencode(params)}"
return url
def save_created_state(state):
pass
def is_valid_state(state):
return True
def get_token(code):
client_auth = requests.auth.HTTPBasicAuth(REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET)
post_data = {"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URI}
response = requests.post(REDDIT_TOKEN_URI,
auth=client_auth,
headers={'User-agent': 'CFB Risk Orders'},
data=post_data)
token_json = response.json()
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
log.error(f"Failed to get Reddit access token.")
log.error(f"{token_json=}")
log.error(f"Exception: {e}")
return
return token_json['access_token']
def get_username(access_token):
headers = {"Authorization": "bearer " + access_token, 'User-agent': 'CFB Risk Orders'}
response = requests.get(REDDIT_ACCOUNT_URI, headers=headers)
# If reddit or discord fail, then don't return anything
try:
return response.json()['name']
except:
return None
###############################################################
#
# Let's go!!!!
#
###############################################################
if __name__ == '__main__':
app.run(debug=True, port=HTTP_PORT)