server.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import os
  2. import ssl
  3. import arrow
  4. import flask_profiler
  5. import sentry_sdk
  6. from flask import Flask, redirect, url_for, render_template, request, jsonify
  7. from flask_admin import Admin
  8. from flask_cors import cross_origin
  9. from flask_login import current_user
  10. from sentry_sdk.integrations.flask import FlaskIntegration
  11. from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
  12. from sentry_sdk.integrations.aiohttp import AioHttpIntegration
  13. from app import paddle_utils
  14. from app.admin_model import SLModelView, SLAdminIndexView
  15. from app.api.base import api_bp
  16. from app.auth.base import auth_bp
  17. from app.config import (
  18. DEBUG,
  19. DB_URI,
  20. FLASK_SECRET,
  21. SENTRY_DSN,
  22. URL,
  23. SHA1,
  24. PADDLE_MONTHLY_PRODUCT_ID,
  25. RESET_DB,
  26. FLASK_PROFILER_PATH,
  27. FLASK_PROFILER_PASSWORD,
  28. SENTRY_FRONT_END_DSN,
  29. )
  30. from app.dashboard.base import dashboard_bp
  31. from app.developer.base import developer_bp
  32. from app.discover.base import discover_bp
  33. from app.extensions import db, login_manager, migrate
  34. from app.jose_utils import get_jwk_key
  35. from app.log import LOG
  36. from app.models import (
  37. Client,
  38. User,
  39. ClientUser,
  40. GenEmail,
  41. RedirectUri,
  42. Subscription,
  43. PlanEnum,
  44. ApiKey,
  45. CustomDomain,
  46. LifetimeCoupon,
  47. Directory,
  48. )
  49. from app.monitor.base import monitor_bp
  50. from app.oauth.base import oauth_bp
  51. if SENTRY_DSN:
  52. LOG.d("enable sentry")
  53. sentry_sdk.init(
  54. dsn=SENTRY_DSN,
  55. integrations=[
  56. FlaskIntegration(),
  57. SqlalchemyIntegration(),
  58. AioHttpIntegration(),
  59. ],
  60. )
  61. # the app is served behin nginx which uses http and not https
  62. os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
  63. def create_app() -> Flask:
  64. app = Flask(__name__)
  65. app.url_map.strict_slashes = False
  66. app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
  67. app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
  68. app.secret_key = FLASK_SECRET
  69. app.config["TEMPLATES_AUTO_RELOAD"] = True
  70. # to avoid conflict with other cookie
  71. app.config["SESSION_COOKIE_NAME"] = "slapp"
  72. init_extensions(app)
  73. register_blueprints(app)
  74. set_index_page(app)
  75. jinja2_filter(app)
  76. setup_error_page(app)
  77. setup_favicon_route(app)
  78. setup_openid_metadata(app)
  79. init_admin(app)
  80. setup_paddle_callback(app)
  81. setup_do_not_track(app)
  82. if FLASK_PROFILER_PATH:
  83. LOG.d("Enable flask-profiler")
  84. app.config["flask_profiler"] = {
  85. "enabled": True,
  86. "storage": {"engine": "sqlite", "FILE": FLASK_PROFILER_PATH},
  87. "basicAuth": {
  88. "enabled": True,
  89. "username": "admin",
  90. "password": FLASK_PROFILER_PASSWORD,
  91. },
  92. "ignore": ["^/static/.*", "/git", "/exception"],
  93. }
  94. flask_profiler.init_app(app)
  95. return app
  96. def fake_data():
  97. LOG.d("create fake data")
  98. # Remove db if exist
  99. if os.path.exists("db.sqlite"):
  100. LOG.d("remove existing db file")
  101. os.remove("db.sqlite")
  102. # Create all tables
  103. db.create_all()
  104. # Create a user
  105. user = User.create(
  106. email="john@wick.com",
  107. name="John Wick",
  108. password="password",
  109. activated=True,
  110. is_admin=True,
  111. otp_secret="base32secret3232",
  112. )
  113. db.session.commit()
  114. LifetimeCoupon.create(code="coupon", nb_used=10)
  115. db.session.commit()
  116. # Create a subscription for user
  117. Subscription.create(
  118. user_id=user.id,
  119. cancel_url="https://checkout.paddle.com/subscription/cancel?user=1234",
  120. update_url="https://checkout.paddle.com/subscription/update?user=1234",
  121. subscription_id="123",
  122. event_time=arrow.now(),
  123. next_bill_date=arrow.now().shift(days=10).date(),
  124. plan=PlanEnum.monthly,
  125. )
  126. db.session.commit()
  127. api_key = ApiKey.create(user_id=user.id, name="Chrome")
  128. api_key.code = "code"
  129. GenEmail.create_new(user.id, "e1@")
  130. GenEmail.create_new(user.id, "e2@")
  131. GenEmail.create_new(user.id, "e3@")
  132. CustomDomain.create(user_id=user.id, domain="ab.cd", verified=True)
  133. CustomDomain.create(
  134. user_id=user.id, domain="very-long-domain.com.net.org", verified=True
  135. )
  136. db.session.commit()
  137. Directory.create(user_id=user.id, name="abcd")
  138. Directory.create(user_id=user.id, name="xyzt")
  139. db.session.commit()
  140. # Create a client
  141. client1 = Client.create_new(name="Demo", user_id=user.id)
  142. client1.oauth_client_id = "client-id"
  143. client1.oauth_client_secret = "client-secret"
  144. client1.published = True
  145. db.session.commit()
  146. RedirectUri.create(client_id=client1.id, uri="https://ab.com")
  147. client2 = Client.create_new(name="Demo 2", user_id=user.id)
  148. client2.oauth_client_id = "client-id2"
  149. client2.oauth_client_secret = "client-secret2"
  150. client2.published = True
  151. db.session.commit()
  152. db.session.commit()
  153. @login_manager.user_loader
  154. def load_user(user_id):
  155. user = User.query.get(user_id)
  156. return user
  157. def register_blueprints(app: Flask):
  158. app.register_blueprint(auth_bp)
  159. app.register_blueprint(monitor_bp)
  160. app.register_blueprint(dashboard_bp)
  161. app.register_blueprint(developer_bp)
  162. app.register_blueprint(oauth_bp, url_prefix="/oauth")
  163. app.register_blueprint(oauth_bp, url_prefix="/oauth2")
  164. app.register_blueprint(discover_bp)
  165. app.register_blueprint(api_bp)
  166. def set_index_page(app):
  167. @app.route("/", methods=["GET", "POST"])
  168. def index():
  169. if current_user.is_authenticated:
  170. return redirect(url_for("dashboard.index"))
  171. else:
  172. return redirect(url_for("auth.login"))
  173. @app.after_request
  174. def after_request(res):
  175. # not logging /static call
  176. if (
  177. not request.path.startswith("/static")
  178. and not request.path.startswith("/admin/static")
  179. and not request.path.startswith("/_debug_toolbar")
  180. ):
  181. LOG.debug(
  182. "%s %s %s %s %s",
  183. request.remote_addr,
  184. request.method,
  185. request.path,
  186. request.args,
  187. res.status_code,
  188. )
  189. res.headers["X-Frame-Options"] = "deny"
  190. return res
  191. def setup_openid_metadata(app):
  192. @app.route("/.well-known/openid-configuration")
  193. @cross_origin()
  194. def openid_config():
  195. res = {
  196. "issuer": URL,
  197. "authorization_endpoint": URL + "/oauth2/authorize",
  198. "token_endpoint": URL + "/oauth2/token",
  199. "userinfo_endpoint": URL + "/oauth2/userinfo",
  200. "jwks_uri": URL + "/jwks",
  201. "response_types_supported": [
  202. "code",
  203. "token",
  204. "id_token",
  205. "id_token token",
  206. "id_token code",
  207. ],
  208. "subject_types_supported": ["public"],
  209. "id_token_signing_alg_values_supported": ["RS256"],
  210. # todo: add introspection and revocation endpoints
  211. # "introspection_endpoint": URL + "/oauth2/token/introspection",
  212. # "revocation_endpoint": URL + "/oauth2/token/revocation",
  213. }
  214. return jsonify(res)
  215. @app.route("/jwks")
  216. @cross_origin()
  217. def jwks():
  218. res = {"keys": [get_jwk_key()]}
  219. return jsonify(res)
  220. def setup_error_page(app):
  221. @app.errorhandler(400)
  222. def page_not_found(e):
  223. return render_template("error/400.html"), 400
  224. @app.errorhandler(401)
  225. def page_not_found(e):
  226. return render_template("error/401.html", current_url=request.full_path), 401
  227. @app.errorhandler(403)
  228. def page_not_found(e):
  229. return render_template("error/403.html"), 403
  230. @app.errorhandler(404)
  231. def page_not_found(e):
  232. return render_template("error/404.html"), 404
  233. @app.errorhandler(Exception)
  234. def error_handler(e):
  235. LOG.exception(e)
  236. return render_template("error/500.html"), 500
  237. def setup_favicon_route(app):
  238. @app.route("/favicon.ico")
  239. def favicon():
  240. return redirect("/static/favicon.ico")
  241. def jinja2_filter(app):
  242. def format_datetime(value):
  243. dt = arrow.get(value)
  244. return dt.humanize()
  245. app.jinja_env.filters["dt"] = format_datetime
  246. @app.context_processor
  247. def inject_stage_and_region():
  248. return dict(
  249. YEAR=arrow.now().year,
  250. URL=URL,
  251. SENTRY_DSN=SENTRY_FRONT_END_DSN,
  252. VERSION=SHA1,
  253. )
  254. def setup_paddle_callback(app: Flask):
  255. @app.route("/paddle", methods=["GET", "POST"])
  256. def paddle():
  257. LOG.debug(
  258. "paddle callback %s %s %s %s %s",
  259. request.form.get("alert_name"),
  260. request.form.get("email"),
  261. request.form.get("customer_name"),
  262. request.form.get("subscription_id"),
  263. request.form.get("subscription_plan_id"),
  264. )
  265. # make sure the request comes from Paddle
  266. if not paddle_utils.verify_incoming_request(dict(request.form)):
  267. LOG.error(
  268. "request not coming from paddle. Request data:%s", dict(request.form)
  269. )
  270. return "KO", 400
  271. if (
  272. request.form.get("alert_name") == "subscription_created"
  273. ): # new user subscribes
  274. user_email = request.form.get("email")
  275. user = User.get_by(email=user_email)
  276. if (
  277. int(request.form.get("subscription_plan_id"))
  278. == PADDLE_MONTHLY_PRODUCT_ID
  279. ):
  280. plan = PlanEnum.monthly
  281. else:
  282. plan = PlanEnum.yearly
  283. sub = Subscription.get_by(user_id=user.id)
  284. if not sub:
  285. LOG.d("create a new sub")
  286. Subscription.create(
  287. user_id=user.id,
  288. cancel_url=request.form.get("cancel_url"),
  289. update_url=request.form.get("update_url"),
  290. subscription_id=request.form.get("subscription_id"),
  291. event_time=arrow.now(),
  292. next_bill_date=arrow.get(
  293. request.form.get("next_bill_date"), "YYYY-MM-DD"
  294. ).date(),
  295. plan=plan,
  296. )
  297. else:
  298. LOG.d("update existing sub %s", sub)
  299. sub.cancel_url = request.form.get("cancel_url")
  300. sub.update_url = request.form.get("update_url")
  301. sub.subscription_id = request.form.get("subscription_id")
  302. sub.event_time = arrow.now()
  303. sub.next_bill_date = arrow.get(
  304. request.form.get("next_bill_date"), "YYYY-MM-DD"
  305. ).date()
  306. sub.plan = plan
  307. LOG.debug("User %s upgrades!", user)
  308. db.session.commit()
  309. elif request.form.get("alert_name") == "subscription_updated":
  310. subscription_id = request.form.get("subscription_id")
  311. LOG.debug("Update subscription %s", subscription_id)
  312. sub: Subscription = Subscription.get_by(subscription_id=subscription_id)
  313. sub.event_time = arrow.now()
  314. sub.next_bill_date = arrow.get(
  315. request.form.get("next_bill_date"), "YYYY-MM-DD"
  316. ).date()
  317. db.session.commit()
  318. elif request.form.get("alert_name") == "subscription_cancelled":
  319. subscription_id = request.form.get("subscription_id")
  320. LOG.error("Cancel subscription %s", subscription_id)
  321. sub: Subscription = Subscription.get_by(subscription_id=subscription_id)
  322. if sub:
  323. sub.cancelled = True
  324. db.session.commit()
  325. return "OK"
  326. def init_extensions(app: Flask):
  327. LOG.debug("init extensions")
  328. login_manager.init_app(app)
  329. db.init_app(app)
  330. migrate.init_app(app)
  331. def init_admin(app):
  332. admin = Admin(name="SimpleLogin", template_mode="bootstrap3")
  333. admin.init_app(app, index_view=SLAdminIndexView())
  334. admin.add_view(SLModelView(User, db.session))
  335. admin.add_view(SLModelView(Client, db.session))
  336. admin.add_view(SLModelView(GenEmail, db.session))
  337. admin.add_view(SLModelView(ClientUser, db.session))
  338. def setup_do_not_track(app):
  339. @app.route("/dnt")
  340. def do_not_track():
  341. return """
  342. <script src="/static/local-storage-polyfill.js"></script>
  343. <script>
  344. // Disable GoatCounter if this script is called
  345. store.set('goatcounter-ignore', 't');
  346. alert("GoatCounter disabled");
  347. window.location.href = "/";
  348. </script>
  349. """
  350. if __name__ == "__main__":
  351. app = create_app()
  352. # enable flask toolbar
  353. # app.config["DEBUG_TB_PROFILER_ENABLED"] = True
  354. # app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
  355. #
  356. # toolbar = DebugToolbarExtension(app)
  357. # enable to print all queries generated by sqlalchemy
  358. # app.config["SQLALCHEMY_ECHO"] = True
  359. # warning: only used in local
  360. if RESET_DB:
  361. LOG.warning("reset db, add fake data")
  362. with app.app_context():
  363. fake_data()
  364. if URL.startswith("https"):
  365. LOG.d("enable https")
  366. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
  367. context.load_cert_chain("local_data/cert.pem", "local_data/key.pem")
  368. app.run(debug=True, host="0.0.0.0", port=7777, ssl_context=context)
  369. else:
  370. app.run(debug=True, host="0.0.0.0", port=7777)