Multimedika/Bot_Development
0
1from fastapi import FastAPI, HTTPException, Form2import httpx3import os4from dotenv import load_dotenv5 6# Load environment variables7load_dotenv()8 9app = FastAPI()10 11# Bearer token and base URL for external API (from environment variables)12BEARER_TOKEN = os.getenv("MEDUCINE_API_BEARER_TOKEN")13BASE_URL = os.getenv("BASE_URL")14 15@app.post("/actions/meducine-restapi/auth/login")16async def login(email: str = Form(...), password: str = Form(...)):17 """18 Handles login by sending a request to the external API with the static Bearer token.19 Even though it simulates a login, it uses the static Bearer token for authentication.20 """21 try:22 # Send login request (simulates login but uses static Bearer token)23 response = await make_request(24 url=f"{BASE_URL}/actions/meducine-restapi/auth/login",25 data={"email": email, "password": password},26 method="POST"27 )28 return response29 except Exception as e:30 raise HTTPException(status_code=500, detail=f"Login failed: {str(e)}")31 32 33@app.post("/actions/meducine-restapi/auth/logout")34async def logout(email: str = Form(...)):35 """36 Handles logout using the static Bearer token.37 """38 try:39 # Simulates logging out but uses the static Bearer token40 response = await make_request(41 url=f"{BASE_URL}/actions/meducine-restapi/auth/logout",42 data={"email": email},43 method="POST"44 )45 return {"message": "Logout successful", "response": response}46 except Exception as e:47 raise HTTPException(status_code=500, detail=f"Logout failed: {str(e)}")48 49 50@app.post("/meducine-restapi/user/has-premium-access")51async def check_premium_access(feature: str, email: str = Form(...), password: str = Form(...)):52 """53 Checks if the user has premium access to a feature, using the static Bearer token for authentication.54 """55 try:56 response = await make_request(57 url=f"{BASE_URL}/actions/meducine-restapi/user/has-premium-access",58 data={"email": email, "password": password},59 params={"feature": feature},60 method="POST"61 )62 return response63 except Exception as e:64 raise HTTPException(status_code=500, detail=f"Premium access check failed: {str(e)}")65 66 67async def make_request(url: str, data: dict = None, method: str = "GET", params: dict = None):68 """69 Helper function to make an HTTP request to the external API with the static Bearer token.70 """71 headers = {"Authorization": f"Bearer {BEARER_TOKEN}"}72 73 async with httpx.AsyncClient() as client:74 try:75 if method == "POST":76 response = await client.post(url, data=data, params=params, headers=headers)77 elif method == "GET":78 response = await client.get(url, params=params, headers=headers)79 else:80 raise HTTPException(status_code=405, detail="Method not allowed")81 82 response.raise_for_status() # Raise exception for 4xx or 5xx errors83 return handle_response(response)84 except httpx.HTTPStatusError as e:85 raise HTTPException(status_code=e.response.status_code, detail=e.response.text)86 except Exception as e:87 raise HTTPException(status_code=500, detail=str(e))88 89 90def handle_response(response: httpx.Response):91 """92 Handles the API response, returning JSON data or raising exceptions based on status codes.93 """94 if response.status_code in range(200, 300):95 return response.json() # Successful request96 elif response.status_code in range(400, 500):97 raise HTTPException(status_code=response.status_code, detail=response.json()) # Client error98 elif response.status_code in range(500, 600):99 raise HTTPException(status_code=response.status_code, detail="Server error") # Server error100 else:101 raise HTTPException(status_code=500, detail="Unexpected error")102 103 104 105# Run the application106if __name__ == "__main__":107 import uvicorn108 uvicorn.run(app, host="127.0.0.1", port=8000)109 