diff --git a/server/.env.example b/server/.env.example new file mode 100644 index 0000000..3f5172f --- /dev/null +++ b/server/.env.example @@ -0,0 +1,2 @@ +FLASK_SECRET_KEY= +OPENAI_API_KEY= \ No newline at end of file diff --git a/server/fabric_api_keys.json b/server/fabric_api_keys.json index b3a379d..948eb91 100644 --- a/server/fabric_api_keys.json +++ b/server/fabric_api_keys.json @@ -1,5 +1,6 @@ { "/extwis": { - "eJ4f1e0b-25wO-47f9-97ec-6b5335b2": "Daniel Miessler" + "eJ4f1e0b-25wO-47f9-97ec-6b5335b2": "Daniel Miessler", + "test": "user2" } } diff --git a/server/fabric_api_server.py b/server/fabric_api_server.py index 8f1cf55..ccb265c 100644 --- a/server/fabric_api_server.py +++ b/server/fabric_api_server.py @@ -1,14 +1,24 @@ -# Imports -import openai +import jwt import json +import openai from flask import Flask, request, jsonify from functools import wraps import re import requests +import os +from dotenv import load_dotenv -## Define Flask app app = Flask(__name__) +@app.errorhandler(404) +def not_found(e): + return jsonify({"error": "The requested resource was not found."}), 404 + +@app.errorhandler(500) +def server_error(e): + return jsonify({"error": "An internal server error occurred."}), 500 + + ################################################## ################################################## # @@ -25,10 +35,8 @@ app = Flask(__name__) ## Set authentication on your APIs ## Let's at least have some kind of auth - -# Load your OpenAI API key from a file -with open("openai.key", "r") as key_file: - openai.api_key = key_file.read().strip() +load_dotenv() +openai.api_key = os.getenv("OPENAI_API_KEY") ## Define our own client client = openai.OpenAI(api_key = openai.api_key) @@ -39,6 +47,11 @@ with open("fabric_api_keys.json", "r") as tokens_file: valid_tokens = json.load(tokens_file) +# Read users from the users.json file +with open("users.json", "r") as users_file: + users = json.load(users_file) + + # The function to check if the token is valid def auth_required(f): """ Decorator function to check if the token is valid. @@ -101,7 +114,7 @@ def check_auth_token(token, route): # Check if token is valid for the given route and return corresponding user if route in valid_tokens and token in valid_tokens[route]: - return valid_tokens[route][token] + return users[valid_tokens[route][token]] else: return "Unauthorized: You are not authorized for this API" @@ -196,8 +209,47 @@ def extwis(): assistant_message = response.choices[0].message.content return jsonify({"response": assistant_message}) except Exception as e: - return jsonify({"error": str(e)}), 500 + app.logger.error(f"Error occurred: {str(e)}") + return jsonify({"error": "An error occurred while processing the request."}), 500 + + +@app.route("/register", methods=["POST"]) +def register(): + data = request.get_json() + + username = data["username"] + password = data["password"] + + if username in users: + return jsonify({"error": "Username already exists"}), 400 + + new_user = { + "username": username, + "password": password + } + + users[username] = new_user + + token = jwt.encode({"username": username}, os.getenv("JWT_SECRET"), algorithm="HS256") + + return jsonify({"token": token.decode("utf-8")}) + + +@app.route("/login", methods=["POST"]) +def login(): + data = request.get_json() + + username = data["username"] + password = data["password"] + + if username in users and users[username]["password"] == password: + # Generate a JWT token + token = jwt.encode({"username": username}, os.getenv("JWT_SECRET"), algorithm="HS256") + + return jsonify({"token": token.decode("utf-8")}) + + return jsonify({"error": "Invalid username or password"}), 401 + -# Run the application if __name__ == "__main__": app.run(host="127.0.0.1", port=13337, debug=True) diff --git a/server/fabric_web_interface/fabric_web_server.py b/server/fabric_web_interface/fabric_web_server.py index eab17b6..373cc7d 100644 --- a/server/fabric_web_interface/fabric_web_server.py +++ b/server/fabric_web_interface/fabric_web_server.py @@ -33,19 +33,23 @@ def send_request(prompt, endpoint): url = f"{base_url}{endpoint}" headers = { "Content-Type": "application/json", - "Authorization": "eJ4f1e0b-25wO-47f9-97ec-6b5335b2", + "Authorization": f"Bearer {session['token']}", } data = json.dumps({"input": prompt}) response = requests.post(url, headers=headers, data=data, verify=False) try: - return response.json()["response"] - except KeyError: - return f"Error: You're not authorized for this application." + response = requests.post(url, headers=headers, data=data) + response.raise_for_status() # raises HTTPError if the response status isn't 200 + except requests.ConnectionError: + return "Error: Unable to connect to the server." + except requests.HTTPError as e: + return f"Error: An HTTP error occurred: {str(e)}" + app = Flask(__name__) -app.secret_key = "your_secret_key" +app.secret_key = os.getenv("FLASK_SECRET_KEY") @app.route("/favicon.ico") diff --git a/server/fabric_web_interface/templates/index.html b/server/fabric_web_interface/templates/index.html index 6c94012..a0c493a 100644 --- a/server/fabric_web_interface/templates/index.html +++ b/server/fabric_web_interface/templates/index.html @@ -17,7 +17,7 @@
fabric
Enter your content and the API you want to send it to.
+Please enter your content and select the API you want to use:
{{ response }}