Ali2206 commited on
Commit
372de92
·
verified ·
1 Parent(s): 37ca855

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -13
app.py CHANGED
@@ -25,16 +25,16 @@ app = FastAPI()
25
  # CORS Configuration (restrict in production)
26
  app.add_middleware(
27
  CORSMiddleware,
28
- allow_origins=["http://localhost:7860", "https://your-production-domain.com"], # Update for production
29
  allow_credentials=True,
30
  allow_methods=["*"],
31
  allow_headers=["*"],
32
  )
33
 
34
- # API Router (assuming this is defined elsewhere)
35
  api_router = APIRouter()
36
 
37
- # Constants (load from environment variables for security)
38
  BACKEND_URL = os.getenv("BACKEND_URL", "https://rocketfarmstudios-cps-api.hf.space")
39
  ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "yakdhanali97@gmail.com")
40
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "123456")
@@ -42,12 +42,11 @@ MAX_TOKEN_RETRIES = 3
42
  TOKEN_RETRY_DELAY = 2 # seconds
43
  TOKEN_EXPIRY = 3600 # 1 hour default expiry
44
 
45
- # Pydantic model for login payload
46
  class LoginPayload(BaseModel):
47
  username: str
48
  password: str
49
 
50
- # Pydantic model for doctor creation payload
51
  class DoctorPayload(BaseModel):
52
  full_name: str
53
  email: str
@@ -66,11 +65,13 @@ class TokenManager:
66
  try:
67
  async with aiohttp.ClientSession() as session:
68
  payload = LoginPayload(username=ADMIN_EMAIL, password=ADMIN_PASSWORD)
 
69
  async with session.post(
70
  f"{BACKEND_URL}/auth/login",
71
  json=payload.dict(),
72
  timeout=10
73
  ) as response:
 
74
  if response.status == 200:
75
  data = await response.json()
76
  token = data.get("access_token")
@@ -120,7 +121,7 @@ def root():
120
  @app.post("/login")
121
  async def redirect_login(request: Request):
122
  logger.info("Redirecting /login to /auth/login")
123
- return RedirectResponse(url="/auth/login", status_code=307)
124
 
125
  def authenticate_admin(email: str = None, password: str = None):
126
  if email != ADMIN_EMAIL or password != ADMIN_PASSWORD:
@@ -134,6 +135,7 @@ async def async_create_doctor(full_name: str, email: str, license_number: str, s
134
  try:
135
  # Validate inputs
136
  if not all([full_name, email, license_number, specialty, password]):
 
137
  raise HTTPException(status_code=422, detail="All fields are required")
138
 
139
  token = await token_manager.get_token()
@@ -150,6 +152,7 @@ async def async_create_doctor(full_name: str, email: str, license_number: str, s
150
  "Content-Type": "application/json"
151
  }
152
 
 
153
  async with aiohttp.ClientSession() as session:
154
  async with session.post(
155
  f"{BACKEND_URL}/auth/admin/doctors",
@@ -157,9 +160,10 @@ async def async_create_doctor(full_name: str, email: str, license_number: str, s
157
  headers=headers,
158
  timeout=10
159
  ) as response:
 
160
  if response.status == 201:
161
  return "✅ Doctor created successfully!"
162
- elif response.status == 401: # Token might be expired
163
  logger.warning("Token expired, attempting refresh...")
164
  token = await token_manager.refresh_token()
165
  headers["Authorization"] = f"Bearer {token}"
@@ -169,6 +173,7 @@ async def async_create_doctor(full_name: str, email: str, license_number: str, s
169
  headers=headers,
170
  timeout=10
171
  ) as retry_response:
 
172
  if retry_response.status == 201:
173
  return "✅ Doctor created successfully!"
174
  error_detail = await retry_response.text()
@@ -220,14 +225,15 @@ with admin_ui:
220
  gr.Markdown("# Doctor Account Creator")
221
 
222
  with gr.Column():
223
- full_name = gr.Textbox(label="Full Name")
224
- email = gr.Textbox(label="Email")
225
- matricule = gr.Textbox(label="License Number")
226
  specialty = gr.Dropdown(
227
  label="Specialty",
228
- choices=["General Practice", "Cardiology", "Neurology", "Pediatrics"]
 
229
  )
230
- password = gr.Textbox(label="Password", type="password")
231
  submit_btn = gr.Button("Create Account")
232
  output = gr.Textbox(label="Status", interactive=False)
233
 
@@ -259,7 +265,6 @@ async def gradio_queue_data(session_hash: str):
259
 
260
  @app.on_event("startup")
261
  async def startup_event():
262
- """Initialize token but don't fail startup"""
263
  try:
264
  await token_manager.get_token()
265
  logger.info("Initial token fetch successful")
 
25
  # CORS Configuration (restrict in production)
26
  app.add_middleware(
27
  CORSMiddleware,
28
+ allow_origins=["http://localhost:7860", "https://your-production-domain.com"],
29
  allow_credentials=True,
30
  allow_methods=["*"],
31
  allow_headers=["*"],
32
  )
33
 
34
+ # API Router (assuming minimal or no conflicting endpoints)
35
  api_router = APIRouter()
36
 
37
+ # Constants (load from environment variables)
38
  BACKEND_URL = os.getenv("BACKEND_URL", "https://rocketfarmstudios-cps-api.hf.space")
39
  ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "yakdhanali97@gmail.com")
40
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "123456")
 
42
  TOKEN_RETRY_DELAY = 2 # seconds
43
  TOKEN_EXPIRY = 3600 # 1 hour default expiry
44
 
45
+ # Pydantic models
46
  class LoginPayload(BaseModel):
47
  username: str
48
  password: str
49
 
 
50
  class DoctorPayload(BaseModel):
51
  full_name: str
52
  email: str
 
65
  try:
66
  async with aiohttp.ClientSession() as session:
67
  payload = LoginPayload(username=ADMIN_EMAIL, password=ADMIN_PASSWORD)
68
+ logger.debug(f"Sending login request to {BACKEND_URL}/auth/login with payload: {payload.dict()}")
69
  async with session.post(
70
  f"{BACKEND_URL}/auth/login",
71
  json=payload.dict(),
72
  timeout=10
73
  ) as response:
74
+ logger.debug(f"Login response status: {response.status}")
75
  if response.status == 200:
76
  data = await response.json()
77
  token = data.get("access_token")
 
121
  @app.post("/login")
122
  async def redirect_login(request: Request):
123
  logger.info("Redirecting /login to /auth/login")
124
+ return RedirectResponse(url="/admin-auth", status_code=307) # Redirect to Gradio UI
125
 
126
  def authenticate_admin(email: str = None, password: str = None):
127
  if email != ADMIN_EMAIL or password != ADMIN_PASSWORD:
 
135
  try:
136
  # Validate inputs
137
  if not all([full_name, email, license_number, specialty, password]):
138
+ logger.error("Doctor creation failed: All fields are required")
139
  raise HTTPException(status_code=422, detail="All fields are required")
140
 
141
  token = await token_manager.get_token()
 
152
  "Content-Type": "application/json"
153
  }
154
 
155
+ logger.debug(f"Sending doctor creation request to {BACKEND_URL}/auth/admin/doctors with payload: {payload.dict()}")
156
  async with aiohttp.ClientSession() as session:
157
  async with session.post(
158
  f"{BACKEND_URL}/auth/admin/doctors",
 
160
  headers=headers,
161
  timeout=10
162
  ) as response:
163
+ logger.debug(f"Doctor creation response status: {response.status}")
164
  if response.status == 201:
165
  return "✅ Doctor created successfully!"
166
+ elif response.status == 401:
167
  logger.warning("Token expired, attempting refresh...")
168
  token = await token_manager.refresh_token()
169
  headers["Authorization"] = f"Bearer {token}"
 
173
  headers=headers,
174
  timeout=10
175
  ) as retry_response:
176
+ logger.debug(f"Retry doctor creation response status: {retry_response.status}")
177
  if retry_response.status == 201:
178
  return "✅ Doctor created successfully!"
179
  error_detail = await retry_response.text()
 
225
  gr.Markdown("# Doctor Account Creator")
226
 
227
  with gr.Column():
228
+ full_name = gr.Textbox(label="Full Name", placeholder="e.g., Dr. John Doe")
229
+ email = gr.Textbox(label="Email", placeholder="e.g., john.doe@example.com")
230
+ matricule = gr.Textbox(label="License Number", placeholder="e.g., 12345")
231
  specialty = gr.Dropdown(
232
  label="Specialty",
233
+ choices=["General Practice", "Cardiology", "Neurology", "Pediatrics"],
234
+ value="General Practice"
235
  )
236
+ password = gr.Textbox(label="Password", type="password", placeholder="Enter a secure password")
237
  submit_btn = gr.Button("Create Account")
238
  output = gr.Textbox(label="Status", interactive=False)
239
 
 
265
 
266
  @app.on_event("startup")
267
  async def startup_event():
 
268
  try:
269
  await token_manager.get_token()
270
  logger.info("Initial token fetch successful")