66 lines
2.8 KiB
Python
66 lines
2.8 KiB
Python
import http.server
|
|
import urllib.request
|
|
import base64
|
|
import json
|
|
|
|
PORT = 8080
|
|
# Cambia esto por tu URL de Harbor real
|
|
HARBOR_URL = "https://harbor.midominio.com"
|
|
|
|
class ProxyHandler(http.server.SimpleHTTPRequestHandler):
|
|
def do_GET(self):
|
|
# Si la petición va dirigida a la API, la redirigimos a Harbor haciendo de proxy
|
|
if self.path.startswith("/api/"):
|
|
target_url = HARBOR_URL + self.path
|
|
|
|
# Recuperamos las cabeceras de autorización que envíe el navegador
|
|
auth_header = self.headers.get('Authorization')
|
|
|
|
req = urllib.request.Request(target_url)
|
|
if auth_header:
|
|
req.add_header('Authorization', auth_header)
|
|
|
|
try:
|
|
# Realizamos la petición a Harbor ignorando problemas de certificados internos si los hubiera
|
|
import ssl
|
|
ctx = ssl.create_default_context()
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
|
|
with urllib.request.urlopen(req, context=ctx) as response:
|
|
data = response.read()
|
|
self.send_response(response.status)
|
|
self.send_header('Content-Type', response.headers.get('Content-Type', 'application/json'))
|
|
# Añadimos las cabeceras CORS para que el navegador no se queje nunca más
|
|
self.send_header('Access-Control-Allow-Origin', '*')
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
except urllib.error.HTTPError as e:
|
|
self.send_response(e.code)
|
|
self.end_headers()
|
|
self.wfile.write(e.read())
|
|
except Exception as e:
|
|
self.send_response(500)
|
|
self.end_headers()
|
|
self.wfile.write(str(e).encode('utf-8'))
|
|
else:
|
|
# Para cualquier otra ruta, sirve los archivos estáticos normales (tu HTML)
|
|
super().do_GET()
|
|
|
|
def do_OPTIONS(self):
|
|
# Respondemos automáticamente al preflight de CORS del navegador
|
|
self.send_response(200)
|
|
self.send_header('Access-Control-Allow-Origin', '*')
|
|
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
|
self.send_header('Access-Control-Allow-Headers', 'Authorization, Content-Type')
|
|
self.end_headers()
|
|
|
|
if __name__ == "__main__":
|
|
server_address = ('', PORT)
|
|
httpd = http.server.HTTPServer(server_address, ProxyHandler)
|
|
print(f"---------------------------------------------------------")
|
|
print(f"Servidor proxy y web corriendo en http://localhost:{PORT}")
|
|
print(f"---------------------------------------------------------")
|
|
print(f"\nUse la URL http://localhost:{PORT} para Harbor\nen vez de {HARBOR_URL}")
|
|
httpd.serve_forever()
|