mazda_webservice.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from requests_oauthlib import OAuth2Session
  2. from flask import Flask, request, redirect, session, url_for, render_template
  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. cfg = mazda_upload.cfg
  9. @app.route("/")
  10. def demo():
  11. github = OAuth2Session(client_id)
  12. authorization_url, state = github.authorization_url(authorization_base_url)
  13. # State is used to prevent CSRF, keep this for later.
  14. session['oauth_state'] = state
  15. return redirect(authorization_url)
  16. # Step 2: User authorization, this happens on the provider.
  17. @app.route("/callback", methods=["GET"])
  18. def callback():
  19. """ Step 3: Retrieving an access token.
  20. The user has been redirected back from the provider to your registered
  21. callback URL. With this redirection comes an authorization code included
  22. in the redirect URL. We will use that to obtain an access token.
  23. """
  24. github = OAuth2Session(client_id, state=session['oauth_state'])
  25. token = github.fetch_token(token_url, client_secret=client_secret,
  26. authorization_response=request.url)
  27. session['oauth_token'] = token
  28. return redirect(url_for('.profile'))
  29. @app.route("/profile", methods=["GET"])
  30. def profile():
  31. """Fetching a protected resource using an OAuth 2 token.
  32. """
  33. github = OAuth2Session(client_id, token=session['oauth_token'])
  34. return jsonify(github.get('https://api.github.com/user').json())
  35. if __name__ == "__main__":
  36. # This allows us to use a plain HTTP callback
  37. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
  38. app.secret_key = os.urandom(24)
  39. app.run(debug=True)