-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
320 lines (273 loc) · 10.5 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
"""Entry point for the application."""
import datetime
import importlib
import logging
import os
from datetime import timezone
import click
import jwt
from flask import Flask, g, request
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from growthbook import GrowthBook
from sqlalchemy import MetaData, inspect
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import DropTable
from waitress import serve
import caching
import config
import model
from apis import api
from apis.authentication import UnauthenticatedException, authentication, authorization
from apis.exception import ValidationException
# from pyfairdatatools import __version__
bcrypt = Bcrypt()
# Add Cascade to Table Drop Call in destroy-schema CLI command
@compiles(DropTable, "postgresql")
def _compile_drop_table(element, compiler):
return f"{compiler.visit_drop_table(element)} CASCADE"
def create_app(config_module=None, loglevel="INFO"):
"""Initialize the core application."""
# create and configure the app
app = Flask(__name__)
# `full` if you want to see all the details
app.config["SWAGGER_UI_DOC_EXPANSION"] = "none"
app.config["RESTX_MASK_SWAGGER"] = False
# set up logging
logging.basicConfig(level=getattr(logging, loglevel))
# Initialize config
app.config.from_object(config_module or "config")
# app.register_blueprint(api)
# TODO - fix this
# csrf = CSRFProtect()
# csrf.init_app(app)
if config.FAIRHUB_SECRET:
if len(config.FAIRHUB_SECRET) < 32:
raise RuntimeError("FAIRHUB_SECRET must be at least 32 characters long")
else:
raise RuntimeError("FAIRHUB_SECRET not set")
if config.FAIRHUB_DATABASE_URL:
# if "TESTING" in app_config and app_config["TESTING"]:
# pass
# else:
# print("DATABASE_URL: ", app.config["DATABASE_URL"])
# app.config["SQLALCHEMY_DATABASE_URI"] = app.config["DATABASE_URL"]
app.config["SQLALCHEMY_DATABASE_URI"] = config.FAIRHUB_DATABASE_URL
else:
# throw error
raise RuntimeError("FAIRHUB_DATABASE_URL not set")
model.db.init_app(app)
api.init_app(app)
bcrypt.init_app(app)
caching.cache.init_app(app)
cors_origins = [
"https://brave-ground-.*-.*.centralus.2.azurestaticapps.net", # noqa E501 # pylint: disable=line-too-long # pylint: disable=anomalous-backslash-in-string
"https://staging.app.fairhub.io",
"https://app.fairhub.io",
"https://staging.fairhub.io",
"https://fairhub.io",
]
if app.debug:
cors_origins.extend(["http://localhost:3000"])
# Only allow CORS origin for localhost:3000
# and any subdomain of azurestaticapps.net/
CORS(
app,
resources={
"/*": {
"origins": cors_origins,
}
},
allow_headers=[
"Content-Type",
"Authorization",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Credentials",
],
supports_credentials=True,
)
# app.config[
# "CORS_ALLOW_HEADERS"
# ] = "Content-Type, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Credentials"
# app.config[
# "CORS_EXPOSE_HEADERS"
# ] = "Content-Type, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Credentials"
# app.config["CORS_SUPPORTS_CREDENTIALS"] = True
# CORS(app, resources={r"/*": {"origins": "*", "send_wildcard": True}})
@app.cli.command("create-schema")
def create_schema():
"""Create the database schema."""
engine = model.db.session.get_bind()
metadata = MetaData()
metadata.reflect(bind=engine)
table_names = [table.name for table in metadata.tables.values()]
if len(table_names) == 0:
with engine.begin():
model.db.create_all()
@app.cli.command("destroy-schema")
def destroy_schema():
"""Create the database schema."""
# If DB is Azure, Skip
if config.FAIRHUB_DATABASE_URL.find("azure") > -1:
return
engine = model.db.session.get_bind()
with engine.begin():
model.db.drop_all()
@app.cli.command("cycle-schema")
def cycle_schema():
"""Destroy then re-create the database schema."""
# If DB is Azure, Skip
if config.FAIRHUB_DATABASE_URL.find("azure") > -1:
return
engine = model.db.session.get_bind()
metadata = MetaData()
metadata.reflect(bind=engine)
table_names = [table.name for table in metadata.tables.values()]
if len(table_names) == 0:
with engine.begin():
model.db.drop_all()
model.db.create_all()
@app.cli.command("list-schemas")
def list_schemas():
engine = model.db.session.get_bind()
inspector = inspect(engine)
schema_names = inspector.get_schema_names()
print("SCHEMAS")
for schema_name in schema_names:
print(schema_name)
@app.cli.command("inspect-schema")
@click.argument("schema")
def inspect_schema(schema=None):
"""Print database schemas, tables, and columns to CLI.
Optional argument schema. Default all schemas inspected.
"""
engine = model.db.session.get_bind()
inspector = inspect(engine)
schema_names = inspector.get_schema_names()
for schema_name in schema_names:
if schema is None or schema == schema_name:
print("-" * 38)
print(f"SCHEMA: {schema_name}")
print("-" * 38)
for table_name in inspector.get_table_names(schema=schema_name):
print(f" Table: {table_name}")
for column in inspector.get_columns(table_name, schema=schema_name):
print(f" Column: {column['name']}")
for k, v in column.items():
print(f" {k:<16}{str(v):>16}")
print("\n ", "-" * 36)
@app.before_request
def on_before_request(): # pylint: disable = inconsistent-return-statements
if request.method == "OPTIONS":
return
try:
authentication()
authorization()
# create growthbook instance
g.gb = GrowthBook(
api_host="https://cdn.growthbook.io",
client_key=config.FAIRHUB_GROWTHBOOK_CLIENT_KEY,
)
# load feature flags
g.gb.load_features()
except UnauthenticatedException:
return "Authentication is required", 401
@app.after_request
def on_after_request(resp):
# destroy growthbook instance
if hasattr(g, "gb"):
g.gb.destroy()
public_routes = [
"/auth",
"/docs",
"/echo",
"/swaggerui",
"/swagger.json",
"/favicon.ico",
]
for route in public_routes:
if request.path.startswith(route):
return resp
if "token" not in request.cookies:
return resp
token: str = request.cookies.get("token") or "" # type: ignore
# Determine the appropriate configuration module based on the testing context
if os.environ.get("FLASK_ENV") == "testing":
config_module_name = "pytest_config"
else:
config_module_name = "config"
config_module = importlib.import_module(config_module_name)
if os.environ.get("FLASK_ENV") == "testing":
# If testing, use the 'TestConfig' class for accessing 'secret'
config = config_module.TestConfig
else:
# If not testing, directly use the 'config' module
config = config_module
try:
decoded = jwt.decode(token, config.FAIRHUB_SECRET, algorithms=["HS256"])
except jwt.ExpiredSignatureError:
resp.set_cookie(
"token",
"",
secure=True,
httponly=True,
samesite="None",
expires=datetime.datetime.now(timezone.utc),
)
return resp
token_blacklist = model.TokenBlacklist.query.get(decoded["jti"])
if token_blacklist:
resp.delete_cookie("token")
return resp
expired_in = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=180
)
new_token = jwt.encode(
{"user": decoded["user"], "exp": expired_in, "jti": decoded["jti"]},
config.FAIRHUB_SECRET,
algorithm="HS256",
)
resp.set_cookie("token", new_token, secure=True, httponly=True, samesite="None")
app.logger.info("after request")
app.logger.info(request.headers.get("Origin"))
resp.headers["Access-Control-Allow-Origin"] = request.headers.get("Origin")
resp.headers["Access-Control-Allow-Credentials"] = "true"
# resp.headers[
# "Access-Control-Allow-Headers"
# ] = "Content-Type, Authorization, Access-Control-Allow-Origin,
# Access-Control-Allow-Credentials"
# resp.headers[
# "Access-Control-Expose-Headers"
# ] = "Content-Type, Authorization, Access-Control-Allow-Origin,
# Access-Control-Allow-Credentials"
app.logger.info(resp.headers)
return resp
@app.errorhandler(ValidationException)
def validation_exception_handler(error):
return error.args[0], 422
with app.app_context():
engine = model.db.session.get_bind()
metadata = MetaData()
metadata.reflect(bind=engine)
table_names = [table.name for table in metadata.tables.values()]
# The alembic table is created by default, so we need to check for more than 1 table
if len(table_names) <= 1:
with engine.begin():
model.db.create_all()
return app
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
"-P", "--port", default=5000, type=int, help="Port to listen on"
)
parser.add_argument("-H", "--host", default="0.0.0.0", type=str, help="Host")
parser.add_argument(
"-L", "--loglevel", default="INFO", type=str, help="Logging level"
)
args = parser.parse_args()
port = args.port
host = args.host
loglevel = args.loglevel
flask_app = create_app(loglevel=loglevel)
serve(flask_app, port=port, host=host)