app.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import json # noqa
  2. import os
  3. from flask import Flask, redirect, request, session, url_for
  4. from flask_oauth import OAuth
  5. BASE_URL = os.environ.get("BASE_URL", "http://dev.getsentry.net:8000")
  6. CLIENT_ID = os.environ.get("CLIENT_ID")
  7. CLIENT_SECRET = os.environ.get("CLIENT_SECRET")
  8. REDIRECT_URI = "/authorized"
  9. SECRET_KEY = "development key"
  10. DEBUG = True
  11. app = Flask(__name__)
  12. app.debug = DEBUG
  13. app.secret_key = SECRET_KEY
  14. oauth = OAuth()
  15. sentry = oauth.remote_app(
  16. "sentry",
  17. base_url=BASE_URL,
  18. authorize_url=f"{BASE_URL}/oauth/authorize/",
  19. request_token_url=None,
  20. request_token_params={
  21. "scope": "project:releases event:read org:read org:write",
  22. "response_type": "code",
  23. },
  24. access_token_url=f"{BASE_URL}/oauth/token/",
  25. access_token_method="POST",
  26. access_token_params={"grant_type": "authorization_code"},
  27. consumer_key=CLIENT_ID,
  28. consumer_secret=CLIENT_SECRET,
  29. )
  30. @app.route("/")
  31. def index():
  32. access_token = session.get("access_token")
  33. if access_token is None:
  34. return ("<h1>Who are you?</h1>" '<p><a href="{}">Login with Sentry</a></p>').format(
  35. url_for("login")
  36. )
  37. from urllib2 import Request, URLError, urlopen
  38. headers = {"Authorization": f"Bearer {access_token}"}
  39. req = Request(f"{BASE_URL}/api/0/organizations/", None, headers)
  40. try:
  41. res = urlopen(req)
  42. except URLError as e:
  43. if e.code == 401:
  44. # Unauthorized - bad token
  45. session.pop("access_token", None)
  46. return redirect(url_for("login"))
  47. return f"{e}\n{e.read()}"
  48. return ("<h1>Hi, {}!</h1>" "<pre>{}</pre>").format(
  49. json.loads(session["user"])["email"], json.dumps(json.loads(res.read()), indent=2)
  50. )
  51. @app.route("/login")
  52. def login():
  53. callback = url_for("authorized", _external=True)
  54. return sentry.authorize(callback=callback)
  55. @app.route(REDIRECT_URI)
  56. @sentry.authorized_handler
  57. def authorized(resp):
  58. if "error" in request.args:
  59. return ("<h1>Error</h1>" "<p>{}</p>" '<p><a href="{}">Try again</a></p>').format(
  60. request.args["error"], url_for("login")
  61. )
  62. access_token = resp["access_token"]
  63. session["access_token"] = access_token
  64. session["user"] = json.dumps(resp["user"])
  65. return redirect(url_for("index"))
  66. @sentry.tokengetter
  67. def get_access_token():
  68. return session.get("access_token")
  69. def main():
  70. app.run()
  71. if __name__ == "__main__":
  72. main()