mazda_webservice.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. from dataclasses import dataclass
  2. from requests_oauthlib import OAuth2Session
  3. from oauthlib.oauth2.rfc6749.errors import OAuth2Error
  4. from flask import Flask, redirect, request, session
  5. from datetime import datetime
  6. import json
  7. import os
  8. import mazda_upload
  9. @dataclass
  10. class Token:
  11. access_token: str
  12. token_type: str
  13. refresh_token: str
  14. expires_in: int
  15. sub: str
  16. iss: str
  17. iat: int
  18. defaultDomain: str
  19. userGuid: str
  20. organisations: list[str]
  21. jti: str
  22. scope: list[str]
  23. expires_at: float
  24. app = Flask(__name__)
  25. cfg: mazda_upload.MazdaConfig = mazda_upload.cfg
  26. base_dir = "C:/projekte/mazda/"
  27. def token_save(token):
  28. session["oauth_token"] = token
  29. with open(base_dir + "temp/token.json", "w") as fwh:
  30. json.dump(token, fwh, indent=2)
  31. def token_load() -> Token:
  32. try:
  33. with open(base_dir + "temp/token.json", "r") as frh:
  34. return json.load(frh)
  35. except FileNotFoundError:
  36. return None
  37. def get_token() -> Token:
  38. if session.get("oauth_token") is None:
  39. session["oauth_token"] = token_load()
  40. if session["oauth_token"] is not None and session["oauth_token"]["expires_at"] < datetime.now().timestamp():
  41. session["oauth_token"] = None
  42. return session["oauth_token"]
  43. @app.route("/")
  44. def demo():
  45. # if token := get_token() is not None:
  46. oauth = OAuth2Session(cfg.client_id, token=get_token())
  47. if oauth.authorized:
  48. return redirect("/profile")
  49. return redirect("/login")
  50. @app.route("/login")
  51. def login():
  52. redirect_uri = request.base_url.rsplit("/", 1)[0] + "/callback"
  53. print(redirect_uri)
  54. oauth = OAuth2Session(cfg.client_id, redirect_uri=redirect_uri)
  55. authorization_url, state = oauth.authorization_url(cfg.domain + cfg.auth_url)
  56. session["oauth_state"] = state
  57. return redirect(authorization_url)
  58. @app.route("/callback", methods=["GET"])
  59. def callback():
  60. state = session.get("oauth_state")
  61. if state is None:
  62. return redirect("/")
  63. print(state)
  64. redirect_uri = request.base_url
  65. print(redirect_uri)
  66. oauth = OAuth2Session(cfg.client_id, state=state, redirect_uri=redirect_uri)
  67. try:
  68. token = oauth.fetch_token(
  69. cfg.domain + cfg.token_url, client_secret=cfg.client_secret, authorization_response=request.url
  70. )
  71. token_save(token)
  72. session["oauth_token"] = token
  73. return redirect("/profile")
  74. except OAuth2Error as e:
  75. print(e)
  76. return redirect("/")
  77. @app.route("/profile", methods=["GET"])
  78. def profile():
  79. oauth = OAuth2Session(cfg.client_id, token=get_token())
  80. if not oauth.authorized:
  81. return redirect("/")
  82. data = mazda_upload.convert_csv(
  83. base_dir + "data/Workshop_Order_Report.csv", base_dir + "temp/mazda_export.json", 2023, 12
  84. )
  85. try:
  86. mazda_upload.upload(oauth, data)
  87. except OAuth2Error:
  88. return redirect("/")
  89. return app.response_class(response=json.dumps(data, indent=2), mimetype="application/json")
  90. if __name__ == "__main__":
  91. # os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
  92. app.secret_key = os.urandom(24)
  93. app.run(
  94. host="0.0.0.0",
  95. port="8085",
  96. ssl_context=(
  97. "config/cert/global-cube.com.crt",
  98. "config/cert/global-cube.com.key",
  99. # "config/cert/intermediate.crt",
  100. ),
  101. debug=True,
  102. )