main.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 decode_token
  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(target_url)
  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. _, credentials = headers["Authorization"].split()
  28. token_data = decode_token(credentials)
  29. if token_data is None or "email" not in token_data:
  30. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  31. user = Users.get_user_by_email(token_data["email"])
  32. if user:
  33. # Only user and admin roles can access
  34. if user.role in ["user", "admin"]:
  35. if path in ["pull", "delete", "push", "copy", "create"]:
  36. # Only admin role can perform actions above
  37. if user.role == "admin":
  38. pass
  39. else:
  40. return (
  41. jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}),
  42. 401,
  43. )
  44. else:
  45. pass
  46. else:
  47. return jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}), 401
  48. else:
  49. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  50. else:
  51. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  52. else:
  53. pass
  54. r = None
  55. headers.pop("Host", None)
  56. headers.pop("Authorization", None)
  57. headers.pop("Origin", None)
  58. headers.pop("Referer", None)
  59. try:
  60. # Make a request to the target server
  61. r = requests.request(
  62. method=request.method,
  63. url=target_url,
  64. data=data,
  65. headers=headers,
  66. stream=True, # Enable streaming for server-sent events
  67. )
  68. r.raise_for_status()
  69. # Proxy the target server's response to the client
  70. def generate():
  71. for chunk in r.iter_content(chunk_size=8192):
  72. yield chunk
  73. response = Response(generate(), status=r.status_code)
  74. # Copy headers from the target server's response to the client's response
  75. for key, value in r.headers.items():
  76. response.headers[key] = value
  77. return response
  78. except Exception as e:
  79. print(e)
  80. error_detail = "Ollama WebUI: Server Connection Error"
  81. if r != None:
  82. print(r.text)
  83. res = r.json()
  84. if "error" in res:
  85. error_detail = f"Ollama: {res['error']}"
  86. print(res)
  87. return (
  88. jsonify(
  89. {
  90. "detail": error_detail,
  91. "message": str(e),
  92. }
  93. ),
  94. 400,
  95. )
  96. if __name__ == "__main__":
  97. app.run(debug=True)