mazda-webservice.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from requests_oauthlib import OAuth2Session
  2. from flask import Flask, request, redirect, session, url_for
  3. from flask.json import jsonify
  4. import os
  5. import mazda_upload
  6. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
  7. app = Flask(__name__)
  8. client_id = "<your client key>"
  9. client_secret = "<your client secret>"
  10. authorization_base_url = 'https://github.com/login/oauth/authorize'
  11. token_url = 'https://github.com/login/oauth/access_token'
  12. @app.route("/")
  13. def demo():
  14. """Step 1: User Authorization.
  15. Redirect the user/resource owner to the OAuth provider (i.e. Github)
  16. using an URL with a few key OAuth parameters.
  17. """
  18. github = OAuth2Session(client_id)
  19. authorization_url, state = github.authorization_url(authorization_base_url)
  20. # State is used to prevent CSRF, keep this for later.
  21. session['oauth_state'] = state
  22. return redirect(authorization_url)
  23. # Step 2: User authorization, this happens on the provider.
  24. @app.route("/callback", methods=["GET"])
  25. def callback():
  26. """ Step 3: Retrieving an access token.
  27. The user has been redirected back from the provider to your registered
  28. callback URL. With this redirection comes an authorization code included
  29. in the redirect URL. We will use that to obtain an access token.
  30. """
  31. github = OAuth2Session(client_id, state=session['oauth_state'])
  32. token = github.fetch_token(token_url, client_secret=client_secret,
  33. authorization_response=request.url)
  34. # At this point you can fetch protected resources but lets save
  35. # the token and show how this is done from a persisted token
  36. # in /profile.
  37. session['oauth_token'] = token
  38. return redirect(url_for('.profile'))
  39. @app.route("/profile", methods=["GET"])
  40. def profile():
  41. """Fetching a protected resource using an OAuth 2 token.
  42. """
  43. github = OAuth2Session(client_id, token=session['oauth_token'])
  44. return jsonify(github.get('https://api.github.com/user').json())
  45. if __name__ == "__main__":
  46. # This allows us to use a plain HTTP callback
  47. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
  48. app.secret_key = os.urandom(24)
  49. app.run(debug=True)