|
from fastapi import FastAPI |
|
from starlette.responses import JSONResponse |
|
from openvpn_api import VPN |
|
|
|
app = FastAPI() |
|
vpn = None |
|
|
|
|
|
app.add_middleware( |
|
CORSMiddleware, |
|
allow_origins=["*"], |
|
allow_credentials=True, |
|
allow_methods=["*"], |
|
allow_headers=["*"], |
|
) |
|
|
|
@app.post("/start") |
|
def start_vpn(): |
|
global vpn |
|
try: |
|
vpn = VPN('localhost', 7505) |
|
vpn.connect() |
|
|
|
return JSONResponse(content={"status": "connected"}, status_code=200) |
|
except Exception as e: |
|
return JSONResponse(content={"error": f"Failed to connect to VPN: {str(e)}"}, status_code=500) |
|
|
|
@app.post("/stop") |
|
def stop_vpn(): |
|
global vpn |
|
try: |
|
if vpn: |
|
vpn.disconnect() |
|
vpn = None |
|
return JSONResponse(content={"status": "disconnected"}, status_code=200) |
|
except Exception as e: |
|
return JSONResponse(content={"error": f"Failed to disconnect from VPN: {str(e)}"}, status_code=500) |
|
|
|
if __name__ == "__main__": |
|
import uvicorn |
|
uvicorn.run(app, host="0.0.0.0", port=5000) |
|
|