Advertisement
Guest User

Flask python web app

a guest
Jul 14th, 2023
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.44 KB | None | 0 0
  1. import flask
  2. import patreon
  3. import json
  4. import os
  5. from google.cloud import storage
  6.  
  7. app = flask.Flask(__name__)
  8.  
  9. CLIENT_ID = "redacted"
  10. CLIENT_SECRET = "redacted"
  11.  
  12. redirectUri = "https://patronauthenticator-sp4uwbgqwa-uc.a.run.app/authenticate"
  13. loginUri =  "https://www.patreon.com/oauth2/authorize?response_type=code&client_id=" + CLIENT_ID + "&redirect_uri=" + redirectUri
  14.  
  15. storageClient = storage.Client()
  16. bucketName = "redacted"
  17. bucket = storageClient.bucket(bucketName)
  18.  
  19. #Where MC redirects players. This will then redirect the user to the Patreon oauth2 authroization site, which will then redirect to /authenticate
  20. @app.route("/login", methods=["GET"])
  21. def login():
  22.     args = flask.request.args
  23.     if "mc_uuid" in args:
  24.         mcUsername = args["mc_uuid"]
  25.         return flask.redirect(loginUri + "&state=" + mcUsername)
  26.     else:
  27.         print("Insufficient arguments: required 'mc_uuid'")
  28.         return "Insufficient arguments: required 'mc_uuid'"
  29.  
  30. # When Minecraft launches, the game will check if the current user's UUID matches any entry in the authenticated.json file. If they do, we sent a validated response, and if not, we send a not_validated response
  31. @app.route("/validate", methods = ["GET"])
  32. def validate():
  33.     args = flask.request.args
  34.     if "mc_uuid" in args:
  35.         mcUUID = args["mc_uuid"]
  36.         file = openBlobFile("authenticated.json", "r")
  37.         try:  
  38.             data = json.load(file)
  39.         except:
  40.             data = []
  41.         for object in data:
  42.             if "mc_uuid" in object and object["mc_uuid"] == mcUUID:
  43.                 file.close();
  44.                 return {
  45.                     "result": "validated"
  46.                 }
  47.            
  48.         file.close();
  49.    
  50.         return {
  51.             "result": "not_validated"
  52.         }
  53.     else:
  54.         print("Insufficient arguments: required 'mc_uuid'")
  55.         return flask.make_response({
  56.             "error": "invalid_arguments"
  57.         }, 400)
  58.  
  59. # Now that we have the user's patron code, we can get their email and their pledges. If they have any pledges, we'll add them (and their MC uuid) to a json file
  60. @app.route("/authenticate", methods=["GET"])
  61. def authenticate():
  62.     args = flask.request.args
  63.     if "error" not in args:
  64.         if "code" in args and "state" in args:
  65.             patronCode = args["code"]
  66.             mcUUID = args["state"]
  67.  
  68.             oauthClient = patreon.OAuth(CLIENT_ID, CLIENT_SECRET)
  69.             tokens = oauthClient.get_tokens(patronCode, redirectUri)
  70.             accessToken =  tokens["access_token"]
  71.  
  72.             apiClient = patreon.API(accessToken)
  73.             # Where everything is going wrong
  74.             userResponse = apiClient.fetch_user()
  75.             print("Response:", userResponse)
  76.  
  77.             if type(userResponse) is dict:
  78.                 if "errors" in userResponse:
  79.                     return logUserAndDisplayError(None, mcUUID)
  80.             elif type(userResponse) is patreon.jsonapi.parser.JSONAPIParser:
  81.                 user = userResponse.data()
  82.                 email = user.attribute("email")
  83.                 pledges = user.relationship("pledges")
  84.                 print("Trying to authenticate:", email)
  85.                 print("Users pledges:", pledges)
  86.                 pledge = pledges[0] if pledges and len(pledges) > 0 else None
  87.                 if pledge != None:
  88.                     readFile = openBlobFile("authenticated.json", "r")
  89.                     try:  
  90.                         data = json.load(readFile)
  91.                     except:
  92.                         data = []
  93.                     readFile.close()
  94.  
  95.                     for object in data:
  96.                         if "email" in object and object["email"] == email:
  97.                             return flask.render_template("error_alreadyvalidated.html"), 302
  98.                        
  99.                     data.append({
  100.                         "email": email,
  101.                         "mc_uuid": mcUUID
  102.                     })
  103.  
  104.                     bucket.blob("authenticated.json").delete()
  105.  
  106.                     file = openBlobFile("authenticated.json", "w")
  107.  
  108.                     output = json.dumps(data)
  109.                     file.write(output)
  110.  
  111.                     file.close()
  112.  
  113.                     return flask.render_template("success.html"), 302
  114.                 else:
  115.                     # If somehow, a user gets access to a BETA build and tries to authenticate themselves, log them in a seperate txt file
  116.                    return logUserAndDisplayError(email, mcUUID)
  117.             else:
  118.                 print("Something went wrong, userReponse:", userResponse)
  119.                 return "Something went wrong!"
  120.         else:
  121.             print("Insufficient arguments: required 'code' and 'state'")
  122.             return flask.make_response("Insufficient arguments: required 'code' and 'state'", 400)
  123.     else:
  124.         print("Error:", args["error"])
  125.         return "Error: " + args["error"]
  126.    
  127. def logUserAndDisplayError(email, mcUUID):
  128.     file = openBlobFile("nonpatron.txt", "w")
  129.     file.write("\n\n")
  130.     if email is None:
  131.         file.write("No Email\n")
  132.     else:
  133.         file.write("Email: " + email + "\n")
  134.     file.write("MC UUID: " + mcUUID)
  135.     return flask.render_template("error_notapatron.html"), 302
  136.  
  137. def openBlobFile(name, method):
  138.     blob = bucket.blob(name)
  139.     return blob.open(method)
  140.  
  141. if __name__ == "__main__":
  142.     app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement