server.py 13 KB

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