old_main.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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("/url", methods=["GET"])
  16. def get_ollama_api_url():
  17. headers = dict(request.headers)
  18. if "Authorization" in headers:
  19. _, credentials = headers["Authorization"].split()
  20. token_data = decode_token(credentials)
  21. if token_data is None or "email" not in token_data:
  22. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  23. user = Users.get_user_by_email(token_data["email"])
  24. if user and user.role == "admin":
  25. return (
  26. jsonify({"OLLAMA_API_BASE_URL": TARGET_SERVER_URL}),
  27. 200,
  28. )
  29. else:
  30. return (
  31. jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}),
  32. 401,
  33. )
  34. else:
  35. return (
  36. jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}),
  37. 401,
  38. )
  39. @app.route("/url/update", methods=["POST"])
  40. def update_ollama_api_url():
  41. headers = dict(request.headers)
  42. data = request.get_json(force=True)
  43. if "Authorization" in headers:
  44. _, credentials = headers["Authorization"].split()
  45. token_data = decode_token(credentials)
  46. if token_data is None or "email" not in token_data:
  47. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  48. user = Users.get_user_by_email(token_data["email"])
  49. if user and user.role == "admin":
  50. TARGET_SERVER_URL = data["url"]
  51. return (
  52. jsonify({"OLLAMA_API_BASE_URL": TARGET_SERVER_URL}),
  53. 200,
  54. )
  55. else:
  56. return (
  57. jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}),
  58. 401,
  59. )
  60. else:
  61. return (
  62. jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}),
  63. 401,
  64. )
  65. @app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE"])
  66. @app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE"])
  67. def proxy(path):
  68. # Combine the base URL of the target server with the requested path
  69. target_url = f"{TARGET_SERVER_URL}/{path}"
  70. print(target_url)
  71. # Get data from the original request
  72. data = request.get_data()
  73. headers = dict(request.headers)
  74. # Basic RBAC support
  75. if WEBUI_AUTH:
  76. if "Authorization" in headers:
  77. _, credentials = headers["Authorization"].split()
  78. token_data = decode_token(credentials)
  79. if token_data is None or "email" not in token_data:
  80. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  81. user = Users.get_user_by_email(token_data["email"])
  82. if user:
  83. # Only user and admin roles can access
  84. if user.role in ["user", "admin"]:
  85. if path in ["pull", "delete", "push", "copy", "create"]:
  86. # Only admin role can perform actions above
  87. if user.role == "admin":
  88. pass
  89. else:
  90. return (
  91. jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}),
  92. 401,
  93. )
  94. else:
  95. pass
  96. else:
  97. return jsonify({"detail": ERROR_MESSAGES.ACCESS_PROHIBITED}), 401
  98. else:
  99. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  100. else:
  101. return jsonify({"detail": ERROR_MESSAGES.UNAUTHORIZED}), 401
  102. else:
  103. pass
  104. r = None
  105. headers.pop("Host", None)
  106. headers.pop("Authorization", None)
  107. headers.pop("Origin", None)
  108. headers.pop("Referer", None)
  109. try:
  110. # Make a request to the target server
  111. r = requests.request(
  112. method=request.method,
  113. url=target_url,
  114. data=data,
  115. headers=headers,
  116. stream=True, # Enable streaming for server-sent events
  117. )
  118. r.raise_for_status()
  119. # Proxy the target server's response to the client
  120. def generate():
  121. for chunk in r.iter_content(chunk_size=8192):
  122. yield chunk
  123. response = Response(generate(), status=r.status_code)
  124. # Copy headers from the target server's response to the client's response
  125. for key, value in r.headers.items():
  126. response.headers[key] = value
  127. return response
  128. except Exception as e:
  129. print(e)
  130. error_detail = "Ollama WebUI: Server Connection Error"
  131. if r != None:
  132. print(r.text)
  133. res = r.json()
  134. if "error" in res:
  135. error_detail = f"Ollama: {res['error']}"
  136. print(res)
  137. return (
  138. jsonify(
  139. {
  140. "detail": error_detail,
  141. "message": str(e),
  142. }
  143. ),
  144. 400,
  145. )
  146. if __name__ == "__main__":
  147. app.run(debug=True)