-
Notifications
You must be signed in to change notification settings - Fork 43
/
app.py
322 lines (258 loc) · 10.6 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
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
from bigcommerce.api import BigcommerceApi
import dotenv
import flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
import os
# do __name__.split('.')[0] if initialising from a file not at project root
app = flask.Flask(__name__)
# Look for a .env file
if os.path.exists('.env'):
dotenv.load_dotenv('.env')
# Load configuration from environment, with defaults
app.config['DEBUG'] = True if os.getenv('DEBUG') == 'True' else False
app.config['LISTEN_HOST'] = os.getenv('LISTEN_HOST', '0.0.0.0')
app.config['LISTEN_PORT'] = int(os.getenv('LISTEN_PORT', '5000'))
app.config['APP_URL'] = os.getenv('APP_URL', 'http://localhost:5000') # must be https to avoid browser issues
app.config['APP_CLIENT_ID'] = os.getenv('APP_CLIENT_ID')
app.config['APP_CLIENT_SECRET'] = os.getenv('APP_CLIENT_SECRET')
app.config['SESSION_SECRET'] = os.getenv('SESSION_SECRET', os.urandom(64))
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///data/hello_world.sqlite').replace("postgres://", "postgresql://", 1)
app.config['SQLALCHEMY_ECHO'] = app.config['DEBUG']
app.config['SESSION_COOKIE_SAMESITE'] = "None"
app.config['SESSION_COOKIE_SECURE'] = True
# Setup secure cookie secret
app.secret_key = app.config['SESSION_SECRET']
# Setup db
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
bc_id = db.Column(db.Integer, nullable=False)
email = db.Column(db.String(120), nullable=False)
storeusers = relationship("StoreUser", backref="user")
def __init__(self, bc_id, email):
self.bc_id = bc_id
self.email = email
def __repr__(self):
return '<User id=%d bc_id=%d email=%s>' % (self.id, self.bc_id, self.email)
class StoreUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
store_id = db.Column(db.Integer, db.ForeignKey('store.id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
admin = db.Column(db.Boolean, nullable=False, default=False)
def __init__(self, store, user, admin=False):
self.store_id = store.id
self.user_id = user.id
self.admin = admin
def __repr__(self):
return '<StoreUser id=%d email=%s user_id=%s store_id=%d admin=%s>' \
% (self.id, self.user.email, self.user_id, self.store.store_id, self.admin)
class Store(db.Model):
id = db.Column(db.Integer, primary_key=True)
store_hash = db.Column(db.String(16), nullable=False, unique=True)
access_token = db.Column(db.String(128), nullable=False)
scope = db.Column(db.Text(), nullable=False)
admin_storeuser_id = relationship("StoreUser",
primaryjoin="and_(StoreUser.store_id==Store.id, StoreUser.admin==True)")
storeusers = relationship("StoreUser", backref="store")
def __init__(self, store_hash, access_token, scope):
self.store_hash = store_hash
self.access_token = access_token
self.scope = scope
def __repr__(self):
return '<Store id=%d store_hash=%s access_token=%s scope=%s>' \
% (self.id, self.store_hash, self.access_token, self.scope)
#
# Error handling and helpers
#
def error_info(e):
content = ""
try: # it's probably a HttpException, if you're using the bigcommerce client
content += str(e.headers) + "<br>" + str(e.content) + "<br>"
req = e.response.request
content += "<br>Request:<br>" + req.url + "<br>" + str(req.headers) + "<br>" + str(req.body)
except AttributeError as e: # not a HttpException
content += "<br><br> (This page threw an exception: {})".format(str(e))
return content
@app.errorhandler(500)
def internal_server_error(e):
content = "Internal Server Error: " + str(e) + "<br>"
content += error_info(e)
return content, 500
@app.errorhandler(400)
def bad_request(e):
content = "Bad Request: " + str(e) + "<br>"
content += error_info(e)
return content, 400
def jwt_error(e):
print(f"JWT verification failed: {e}")
return "Payload verification failed!", 401
# Helper for template rendering
def render(template, context):
return flask.render_template(template, **context)
def client_id():
return app.config['APP_CLIENT_ID']
def client_secret():
return app.config['APP_CLIENT_SECRET']
#
# OAuth pages
#
# The Auth Callback URL. See https://developer.bigcommerce.com/api/callback
@app.route('/bigcommerce/callback')
def auth_callback():
# Put together params for token request
code = flask.request.args['code']
context = flask.request.args['context']
scope = flask.request.args['scope']
store_hash = context.split('/')[1]
redirect = app.config['APP_URL'] + flask.url_for('auth_callback')
# Fetch a permanent oauth token. This will throw an exception on error,
# which will get caught by our error handler above.
client = BigcommerceApi(client_id=client_id(), store_hash=store_hash)
token = client.oauth_fetch_token(client_secret(), code, context, scope, redirect)
bc_user_id = token['user']['id']
email = token['user']['email']
access_token = token['access_token']
# Create or update store
store = Store.query.filter_by(store_hash=store_hash).first()
if store is None:
store = Store(store_hash, access_token, scope)
db.session.add(store)
db.session.commit()
else:
store.access_token = access_token
store.scope = scope
db.session.add(store)
db.session.commit()
# If the app was installed before, make sure the old admin user is no longer marked as the admin
oldadminuser = StoreUser.query.filter_by(store_id=store.id, admin=True).first()
if oldadminuser:
oldadminuser.admin = False
db.session.add(oldadminuser)
# Create or update global BC user
user = User.query.filter_by(bc_id=bc_user_id).first()
if user is None:
user = User(bc_user_id, email)
db.session.add(user)
elif user.email != email:
user.email = email
db.session.add(user)
# Create or update store user
storeuser = StoreUser.query.filter_by(user_id=user.id, store_id=store.id).first()
if not storeuser:
storeuser = StoreUser(store, user, admin=True)
else:
storeuser.admin = True
db.session.add(storeuser)
db.session.commit()
# Log user in and redirect to app home
flask.session['storeuserid'] = storeuser.id
return flask.redirect(app.config['APP_URL'])
# The Load URL. See https://developer.bigcommerce.com/api/load
@app.route('/bigcommerce/load')
def load():
# Decode and verify payload
payload = flask.request.args['signed_payload_jwt']
try:
user_data = BigcommerceApi.oauth_verify_payload_jwt(payload, client_secret(), client_id())
except Exception as e:
return jwt_error(e)
bc_user_id = user_data['user']['id']
email = user_data['user']['email']
store_hash = user_data['sub'].split('stores/')[1]
# Lookup store
store = Store.query.filter_by(store_hash=store_hash).first()
if store is None:
return "Store not found!", 401
# Lookup user and create if doesn't exist (this can happen if you enable multi-user
# when registering your app)
user = User.query.filter_by(bc_id=bc_user_id).first()
if user is None:
user = User(bc_user_id, email)
db.session.add(user)
db.session.commit()
storeuser = StoreUser.query.filter_by(user_id=user.id, store_id=store.id).first()
if storeuser is None:
storeuser = StoreUser(store, user)
db.session.add(storeuser)
db.session.commit()
# Log user in and redirect to app interface
flask.session['storeuserid'] = storeuser.id
return flask.redirect(app.config['APP_URL'])
# The Uninstall URL. See https://developer.bigcommerce.com/api/load
@app.route('/bigcommerce/uninstall')
def uninstall():
# Decode and verify payload
payload = flask.request.args['signed_payload_jwt']
try:
user_data = BigcommerceApi.oauth_verify_payload_jwt(payload, client_secret(), client_id())
except Exception as e:
return jwt_error(e)
# Lookup store
store_hash = user_data['sub'].split('stores/')[1]
store = Store.query.filter_by(store_hash=store_hash).first()
if store is None:
return "Store not found!", 401
# Clean up: delete store associated users. This logic is up to you.
# You may decide to keep these records around in case the user installs
# your app again.
storeusers = StoreUser.query.filter_by(store_id=store.id)
for storeuser in storeusers:
db.session.delete(storeuser)
db.session.delete(store)
db.session.commit()
return flask.Response('Deleted', status=204)
# The Remove User Callback URL.
@app.route('/bigcommerce/remove-user')
def remove_user():
payload = flask.request.args['signed_payload_jwt']
try:
user_data = BigcommerceApi.oauth_verify_payload_jwt(payload, client_secret(), client_id())
except Exception as e:
return jwt_error(e)
store_hash = user_data['sub'].split('stores/')[1]
store = Store.query.filter_by(store_hash=store_hash).first()
if store is None:
return "Store not found!", 401
# Lookup user and delete it
bc_user_id = user_data['user']['id']
user = User.query.filter_by(bc_id=bc_user_id).first()
if user is not None:
storeuser = StoreUser.query.filter_by(user_id=user.id, store_id=store.id).first()
db.session.delete(storeuser)
db.session.commit()
return flask.Response('Deleted', status=204)
#
# App interface
#
@app.route('/')
def index():
# Lookup user
storeuser = StoreUser.query.filter_by(id=flask.session['storeuserid']).first()
if storeuser is None:
return "Not logged in!", 401
store = storeuser.store
user = storeuser.user
# Construct api client
client = BigcommerceApi(client_id=client_id(),
store_hash=store.store_hash,
access_token=store.access_token)
# Fetch a few products
products = client.Products.all(limit=10)
# Render page
context = dict()
context['products'] = products
context['user'] = user
context['store'] = store
context['client_id'] = client_id()
context['api_url'] = client.connection.host
return render('index.html', context)
@app.route('/instructions')
def instructions():
if not app.config['DEBUG']:
return "Forbidden - instructions only visible in debug mode"
context = dict()
return render('instructions.html', context)
if __name__ == "__main__":
db.create_all()
app.run(app.config['LISTEN_HOST'], app.config['LISTEN_PORT'])