sachin commited on
Commit
90b38cc
·
1 Parent(s): 4335561
Files changed (2) hide show
  1. src/server/main.py +4 -4
  2. src/server/utils/auth.py +21 -6
src/server/main.py CHANGED
@@ -15,7 +15,8 @@ import requests
15
  from PIL import Image
16
 
17
  # Import from auth.py
18
- from utils.auth import get_current_user, login, TokenResponse, Settings
 
19
 
20
  # Assuming these are in your project structure
21
  from config.tts_config import SPEED, ResponseFormat, config as tts_config
@@ -105,9 +106,8 @@ async def home():
105
  return RedirectResponse(url="/docs")
106
 
107
  @app.post("/v1/token", response_model=TokenResponse)
108
- async def token(user_id: str = Form(...)):
109
- # In production, add proper authentication (e.g., password validation)
110
- return await login(user_id=user_id)
111
 
112
  @app.post("/v1/audio/speech")
113
  @limiter.limit(settings.speech_rate_limit)
 
15
  from PIL import Image
16
 
17
  # Import from auth.py
18
+ #from utils.auth import get_current_user, login, TokenResponse, Settings
19
+ from utils.auth import get_current_user, login, TokenResponse, Settings, LoginRequest
20
 
21
  # Assuming these are in your project structure
22
  from config.tts_config import SPEED, ResponseFormat, config as tts_config
 
106
  return RedirectResponse(url="/docs")
107
 
108
  @app.post("/v1/token", response_model=TokenResponse)
109
+ async def token(login_request: LoginRequest):
110
+ return await login(login_request)
 
111
 
112
  @app.post("/v1/audio/speech")
113
  @limiter.limit(settings.speech_rate_limit)
src/server/utils/auth.py CHANGED
@@ -5,6 +5,7 @@ from fastapi import HTTPException, status, Depends
5
  from pydantic import BaseModel, Field
6
  from pydantic_settings import BaseSettings
7
  from config.logging_config import logger
 
8
 
9
  class Settings(BaseSettings):
10
  api_key_secret: str = Field(..., env="API_KEY_SECRET")
@@ -37,6 +38,17 @@ class TokenResponse(BaseModel):
37
  access_token: str
38
  token_type: str
39
 
 
 
 
 
 
 
 
 
 
 
 
40
  async def create_access_token(user_id: str) -> str:
41
  expire = datetime.utcnow() + timedelta(minutes=settings.token_expiration_minutes)
42
  payload = {"sub": user_id, "exp": expire.timestamp()}
@@ -54,17 +66,15 @@ async def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
54
  try:
55
  logger.info(f"Received token: {token}")
56
  logger.info(f"Verifying token with API_KEY_SECRET: {settings.api_key_secret}")
57
- # Decode with expiration verification disabled to avoid PyJWT bug
58
  payload = jwt.decode(token, settings.api_key_secret, algorithms=["HS256"], options={"verify_exp": False})
59
  logger.info(f"Decoded payload: {payload}")
60
  token_data = TokenPayload(**payload)
61
  user_id = token_data.sub
62
 
63
- if user_id is None:
64
- logger.warning("Token has no 'sub' claim")
65
  raise credentials_exception
66
 
67
- # Manual expiration check
68
  current_time = datetime.utcnow().timestamp()
69
  logger.info(f"Current time: {current_time}, Token exp: {token_data.exp}")
70
  if current_time > token_data.exp:
@@ -87,6 +97,11 @@ async def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
87
  logger.error(f"Unexpected token validation error: {str(e)}")
88
  raise credentials_exception
89
 
90
- async def login(user_id: str) -> TokenResponse:
91
- token = await create_access_token(user_id=user_id)
 
 
 
 
 
92
  return TokenResponse(access_token=token, token_type="bearer")
 
5
  from pydantic import BaseModel, Field
6
  from pydantic_settings import BaseSettings
7
  from config.logging_config import logger
8
+ from typing import Dict
9
 
10
  class Settings(BaseSettings):
11
  api_key_secret: str = Field(..., env="API_KEY_SECRET")
 
38
  access_token: str
39
  token_type: str
40
 
41
+ # Simple in-memory user store (replace with database in production)
42
+ # Format: {username: password}
43
+ USERS_DB: Dict[str, str] = {
44
+ "testuser": "password123",
45
+ "admin": "adminpass"
46
+ }
47
+
48
+ class LoginRequest(BaseModel):
49
+ username: str
50
+ password: str
51
+
52
  async def create_access_token(user_id: str) -> str:
53
  expire = datetime.utcnow() + timedelta(minutes=settings.token_expiration_minutes)
54
  payload = {"sub": user_id, "exp": expire.timestamp()}
 
66
  try:
67
  logger.info(f"Received token: {token}")
68
  logger.info(f"Verifying token with API_KEY_SECRET: {settings.api_key_secret}")
 
69
  payload = jwt.decode(token, settings.api_key_secret, algorithms=["HS256"], options={"verify_exp": False})
70
  logger.info(f"Decoded payload: {payload}")
71
  token_data = TokenPayload(**payload)
72
  user_id = token_data.sub
73
 
74
+ if user_id is None or user_id not in USERS_DB:
75
+ logger.warning(f"Invalid or unknown user: {user_id}")
76
  raise credentials_exception
77
 
 
78
  current_time = datetime.utcnow().timestamp()
79
  logger.info(f"Current time: {current_time}, Token exp: {token_data.exp}")
80
  if current_time > token_data.exp:
 
97
  logger.error(f"Unexpected token validation error: {str(e)}")
98
  raise credentials_exception
99
 
100
+ async def login(login_request: LoginRequest) -> TokenResponse:
101
+ username = login_request.username
102
+ password = login_request.password
103
+ if username not in USERS_DB or USERS_DB[username] != password:
104
+ logger.warning(f"Login failed for user: {username}")
105
+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password")
106
+ token = await create_access_token(user_id=username)
107
  return TokenResponse(access_token=token, token_type="bearer")