main.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from flask import Flask, request, Response, jsonify
  2. from flask_cors import CORS
  3. import requests
  4. import json
  5. from apps.web.models.users import Users
  6. from constants import ERROR_MESSAGES
  7. from utils.utils import extract_token_from_auth_header
  8. from config import OLLAMA_API_BASE_URL, WEBUI_AUTH
  9. app = Flask(__name__)
  10. CORS(
  11. app
  12. ) # Enable Cross-Origin Resource Sharing (CORS) to allow requests from different domains
  13. # Define the target server URL
  14. TARGET_SERVER_URL = OLLAMA_API_BASE_URL
  15. @app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE"])
  16. @app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE"])
  17. def proxy(path):
  18. # Combine the base URL of the target server with the requested path
  19. target_url = f"{TARGET_SERVER_URL}/{path}"
  20. print(path)
  21. # Get data from the original request
  22. data = request.get_data()
  23. headers = dict(request.headers)
  24. # Basic RBAC support
  25. if WEBUI_AUTH:
  26. if "Authorization" in headers:
  27. token = extract_token_from_auth_header(headers["Authorization"])
  28. user = Users.get_user_by_token(token)
  29. if user:
  30. # Only user and admin roles can access
  31. if user.role in ["user", "admin"]:
  32. if path in ["pull", "delete", "push", "copy", "create"]:
  33. # Only admin role can perform actions above
  34. if user.role == "admin":
  35. pass
  36. else:
  37. return (
  38. jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}),
  39. 401,
  40. )
  41. else:
  42. pass
  43. else:
  44. return jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}), 401
  45. else:
  46. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  47. else:
  48. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  49. else:
  50. pass
  51. try:
  52. # Make a request to the target server
  53. target_response = requests.request(
  54. method=request.method,
  55. url=target_url,
  56. data=data,
  57. headers=headers,
  58. stream=True, # Enable streaming for server-sent events
  59. )
  60. target_response.raise_for_status()
  61. # Proxy the target server's response to the client
  62. def generate():
  63. for chunk in target_response.iter_content(chunk_size=8192):
  64. yield chunk
  65. response = Response(generate(), status=target_response.status_code)
  66. # Copy headers from the target server's response to the client's response
  67. for key, value in target_response.headers.items():
  68. response.headers[key] = value
  69. return response
  70. except Exception as e:
  71. return jsonify({"detail": "Server Connection Error", "message": str(e)}), 400
  72. if __name__ == "__main__":
  73. app.run(debug=True)