CORVO-AI commited on
Commit
5a8c7cd
·
verified ·
1 Parent(s): 305d870

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -15
app.py CHANGED
@@ -1,40 +1,83 @@
1
  import requests
2
  from flask import Flask, request, jsonify
 
3
 
4
  app = Flask(__name__)
5
 
6
- # Your PythonAnywhere API endpoint
7
  PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  @app.route('/chat', methods=['POST'])
10
  def chat():
11
  try:
12
- # Ensure the request contains JSON and a "message" key
13
- user_input = request.json.get("message", "") if request.is_json else None
 
 
 
 
 
14
 
15
- if not user_input:
16
- return jsonify({"error": "No message provided in the request."}), 400
17
 
18
- # Create the payload to send to PythonAnywhere
19
- data = {"message": user_input}
 
 
20
 
21
- # Forward the request to PythonAnywhere
22
- response = requests.post(PYTHONANYWHERE_URL, json=data)
 
23
 
24
  if response.status_code == 200:
25
- response_json = response.json()
26
- ai_response = response_json.get("response", "No 'response' key found in the JSON.")
27
- ai_response = ai_response.encode('latin1').decode('utf-8', 'ignore')
28
- return (ai_response)
29
  else:
30
- # Handle errors from PythonAnywhere
31
  return jsonify({
32
  "error": "Error from PythonAnywhere",
33
  "details": response.text
34
  }), response.status_code
35
 
36
  except Exception as e:
37
- # Catch any unexpected errors
38
  return jsonify({"error": "An error occurred", "details": str(e)}), 500
39
 
40
 
 
1
  import requests
2
  from flask import Flask, request, jsonify
3
+ from datetime import datetime
4
 
5
  app = Flask(__name__)
6
 
7
+ # PythonAnywhere API endpoint
8
  PYTHONANYWHERE_URL = "https://omarnuwara.pythonanywhere.com/get-response"
9
 
10
+ # GitHub API and file information (for token validation)
11
+ GITHUB_TOKEN = "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" # Store securely in .env in production
12
+ REPO_OWNER = "omarnuwrar"
13
+ REPO_NAME = "api"
14
+ FILE_PATH = "user.json"
15
+
16
+ # Helper function to fetch user data from GitHub
17
+ def fetch_user_data():
18
+ url = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{FILE_PATH}"
19
+ headers = {
20
+ "Authorization": f"token {GITHUB_TOKEN}",
21
+ "Accept": "application/vnd.github.v3+json",
22
+ }
23
+ response = requests.get(url, headers=headers)
24
+ if response.status_code == 200:
25
+ content = response.json()
26
+ file_content = content["content"]
27
+ file_decoded = base64.b64decode(file_content).decode("utf-8")
28
+ return json.loads(file_decoded)
29
+ else:
30
+ return None
31
+
32
+ # Check if a given token is valid and unexpired
33
+ def validate_token(token):
34
+ user_data = fetch_user_data()
35
+ if not user_data:
36
+ return False, "Unable to fetch user data."
37
+
38
+ for user in user_data:
39
+ if user["token"] == token:
40
+ token_expiration_time = datetime.fromisoformat(user["token_expiration_time"])
41
+ if datetime.now() <= token_expiration_time:
42
+ return True, f"Valid token for {user['first_name']} {user['last_name']}."
43
+ else:
44
+ return False, "Token expired. Please subscribe to continue."
45
+ return False, "Invalid token."
46
+
47
  @app.route('/chat', methods=['POST'])
48
  def chat():
49
  try:
50
+ # Ensure the request contains JSON, a "message" key, and a "token" key
51
+ if not request.is_json:
52
+ return jsonify({"error": "Request must contain JSON."}), 400
53
+
54
+ data = request.json
55
+ user_input = data.get("message")
56
+ token = data.get("token")
57
 
58
+ if not user_input or not token:
59
+ return jsonify({"error": "Both 'message' and 'token' are required."}), 400
60
 
61
+ # Validate the token
62
+ is_valid, validation_message = validate_token(token)
63
+ if not is_valid:
64
+ return jsonify({"error": validation_message}), 401
65
 
66
+ # Forward the request to PythonAnywhere if the token is valid
67
+ payload = {"message": user_input}
68
+ response = requests.post(PYTHONANYWHERE_URL, json=payload)
69
 
70
  if response.status_code == 200:
71
+ ai_response = response.json().get("response", "No response available.")
72
+ return jsonify({"response": ai_response}), 200
 
 
73
  else:
 
74
  return jsonify({
75
  "error": "Error from PythonAnywhere",
76
  "details": response.text
77
  }), response.status_code
78
 
79
  except Exception as e:
80
+ # Catch unexpected errors
81
  return jsonify({"error": "An error occurred", "details": str(e)}), 500
82
 
83