-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_prod.py
187 lines (151 loc) · 5.46 KB
/
app_prod.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
#!/usr/bin/env python
from flask import Flask, abort, request, render_template, session, url_for
from uuid import uuid4
import requests
import requests.auth
import urllib
import re
from urllib.parse import urlparse
from dotenv import load_dotenv
import os
from supabase import create_client, Client
import random
import string
# This version of the app.py was used in production after
# all the gifts were received and ready to be viewed
# https://indiasocial.pythonanywhere.com/reddit_callback
load_dotenv()
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
REDIRECT_URI = os.getenv("REDIRECT_URI")
url = os.getenv("SUPABASE_URL")
key = os.getenv("SUPABASE_KEY")
supabase: Client = create_client(url, key)
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY")
@app.route("/")
def homepage():
authorize_url = make_authorization_url()
return render_template("index.html", authorize_url=authorize_url)
@app.route("/reddit_callback")
def reddit_callback():
error = request.args.get("error", "")
if error:
return "Error: " + error
state = request.args.get("state", "")
if not is_valid_state(state):
# Uh-oh, this request wasn't started by us!
abort(403)
code = request.args.get("code")
access_token = get_token(code)
username = get_username(access_token)
session["username"] = username
response = supabase.table("gifts").select("*").eq("username", username).execute()
if response.data:
gift_sent = 1
else:
gift_sent = 0
return render_template("index.html", username=username, gift_sent=gift_sent)
@app.route("/send_gift", methods=["GET", "POST"])
def send_gift():
if "username" not in session:
return redirect(url_for("homepage"))
confirmation_message = None # Initialize a variable to hold the message
if request.method == "POST":
secret_gift = request.form.get("secret_gift")
username = session["username"]
if not secret_gift:
confirmation_message = "Please provide a valid gift for your Secret Santa!"
return render_template(
"send_gift.html", username=username, message=confirmation_message
)
# Save gift to Supabase
try:
response = (
supabase.table("gifts")
.upsert({"username": username, "secret_gift": secret_gift})
.execute()
)
confirmation_message = "Your gift has been sent successfully!"
except Exception as e:
confirmation_message = "Failed to send gift. Please try again later."
return render_template(
"send_gift.html", username=session["username"], message=confirmation_message
)
@app.route("/view_gift", methods=["GET"])
def view_gift():
if "username" not in session:
return redirect(url_for("homepage"))
username = session["username"]
secret_gift = None # Initialize variable to hold the fetched gift
error_message = None
try:
# Use the provided SQL query to fetch the secret_gift
response = (
supabase.table("final_gifts").select("match_gift").eq("username", username).execute()
)
# Extract the secret_gift from the response if available
if response.data and len(response.data) > 0:
secret_gift = response.data[0]['match_gift']
else:
error_message = "No gift found for your Secret Santa match."
except Exception as e:
error_message = "Failed to retrieve the gift. Please try again later."
# Render the view_gift.html template
return render_template(
"view_gift.html",
username=username,
secret_gift=secret_gift,
error_message=error_message
)
def make_authorization_url():
# Generate a random string for the state parameter
# Save it for use later to prevent xsrf attacks
state = str(uuid4())
save_created_state(state)
params = {
"client_id": CLIENT_ID,
"response_type": "code",
"state": state,
"redirect_uri": REDIRECT_URI,
"duration": "temporary",
"scope": "identity",
}
url = "https://ssl.reddit.com/api/v1/authorize?" + urllib.parse.urlencode(params)
return url
# Left as an exercise to the reader.
# You may want to store valid states in a database or memcache.
def save_created_state(state):
pass
def is_valid_state(state):
return True
def get_token(code):
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
post_data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": REDIRECT_URI,
}
headers = base_headers()
response = requests.post(
"https://ssl.reddit.com/api/v1/access_token",
auth=client_auth,
headers=headers,
data=post_data,
)
token_json = response.json()
return token_json["access_token"]
def get_username(access_token):
headers = base_headers()
headers.update({"Authorization": "bearer " + access_token})
response = requests.get("https://oauth.reddit.com/api/v1/me", headers=headers)
me_json = response.json()
return me_json["name"]
def user_agent():
"""reddit API clients should each have their own, unique user-agent
Ideally, with contact info included."""
return "Secret Santa app by u/UnemployedTechie2021"
def base_headers():
return {"User-Agent": user_agent()}
if __name__ == "__main__":
app.run(debug=True, port=65010)