File size: 4,117 Bytes
0767396
69beac6
 
 
 
 
 
 
 
 
0767396
69beac6
 
 
0767396
69beac6
0767396
 
 
 
 
 
 
 
69beac6
0767396
69beac6
0767396
 
 
69beac6
0767396
 
 
 
 
 
 
 
 
 
 
 
69beac6
0767396
 
 
69beac6
0767396
 
 
 
 
 
 
 
 
 
69beac6
0767396
69beac6
0767396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69beac6
 
 
0767396
69beac6
 
 
 
 
 
 
 
 
 
0767396
 
69beac6
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
from fastapi import FastAPI, HTTPException, Form
import httpx
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

app = FastAPI()

# Bearer token and base URL for external API (from environment variables)
BEARER_TOKEN = os.getenv("MEDUCINE_API_BEARER_TOKEN")
BASE_URL = os.getenv("BASE_URL")

@app.post("/actions/meducine-restapi/auth/login")
async def login(email: str = Form(...), password: str = Form(...)):
    """
    Handles login by sending a request to the external API with the static Bearer token.
    Even though it simulates a login, it uses the static Bearer token for authentication.
    """
    try:
        # Send login request (simulates login but uses static Bearer token)
        response = await make_request(
            url=f"{BASE_URL}/actions/meducine-restapi/auth/login",
            data={"email": email, "password": password},
            method="POST"
        )
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Login failed: {str(e)}")


@app.post("/actions/meducine-restapi/auth/logout")
async def logout(email: str = Form(...)):
    """
    Handles logout using the static Bearer token.
    """
    try:
        # Simulates logging out but uses the static Bearer token
        response = await make_request(
            url=f"{BASE_URL}/actions/meducine-restapi/auth/logout",
            data={"email": email},
            method="POST"
        )
        return {"message": "Logout successful", "response": response}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Logout failed: {str(e)}")


@app.post("/meducine-restapi/user/has-premium-access")
async def check_premium_access(feature: str, email: str = Form(...), password: str = Form(...)):
    """
    Checks if the user has premium access to a feature, using the static Bearer token for authentication.
    """
    try:
        response = await make_request(
            url=f"{BASE_URL}/actions/meducine-restapi/user/has-premium-access",
            data={"email": email, "password": password},
            params={"feature": feature},
            method="POST"
        )
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Premium access check failed: {str(e)}")


async def make_request(url: str, data: dict = None, method: str = "GET", params: dict = None):
    """
    Helper function to make an HTTP request to the external API with the static Bearer token.
    """
    headers = {"Authorization": f"Bearer {BEARER_TOKEN}"}

    async with httpx.AsyncClient() as client:
        try:
            if method == "POST":
                response = await client.post(url, data=data, params=params, headers=headers)
            elif method == "GET":
                response = await client.get(url, params=params, headers=headers)
            else:
                raise HTTPException(status_code=405, detail="Method not allowed")

            response.raise_for_status()  # Raise exception for 4xx or 5xx errors
            return handle_response(response)
        except httpx.HTTPStatusError as e:
            raise HTTPException(status_code=e.response.status_code, detail=e.response.text)
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e))


def handle_response(response: httpx.Response):
    """
    Handles the API response, returning JSON data or raising exceptions based on status codes.
    """
    if response.status_code in range(200, 300):
        return response.json()  # Successful request
    elif response.status_code in range(400, 500):
        raise HTTPException(status_code=response.status_code, detail=response.json())  # Client error
    elif response.status_code in range(500, 600):
        raise HTTPException(status_code=response.status_code, detail="Server error")  # Server error
    else:
        raise HTTPException(status_code=500, detail="Unexpected error")



# Run the application
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)