main.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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, OLLAMA_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 OLLAMA_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. # Make a request to the target server
  52. target_response = requests.request(
  53. method=request.method,
  54. url=target_url,
  55. data=data,
  56. headers=headers,
  57. stream=True, # Enable streaming for server-sent events
  58. )
  59. # Proxy the target server's response to the client
  60. def generate():
  61. for chunk in target_response.iter_content(chunk_size=8192):
  62. yield chunk
  63. response = Response(generate(), status=target_response.status_code)
  64. # Copy headers from the target server's response to the client's response
  65. for key, value in target_response.headers.items():
  66. response.headers[key] = value
  67. return response
  68. if __name__ == "__main__":
  69. app.run(debug=True)