Coverage for api \ auth.py: 0.00%

19 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2025-11-25 15:37 +0330

1""" 

2Authentication and Security for API Endpoints 

3""" 

4 

5from fastapi import Security, HTTPException, status, Request 

6from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials 

7from config import config 

8 

9security = HTTPBearer(auto_error=False) 

10 

11 

12async def verify_token(credentials: HTTPAuthorizationCredentials = Security(security)): 

13 """Verify API token""" 

14 # If no tokens configured, allow access 

15 if not config.API_TOKENS: 

16 return None 

17 

18 # If tokens configured, require authentication 

19 if not credentials: 

20 raise HTTPException( 

21 status_code=status.HTTP_401_UNAUTHORIZED, 

22 detail="Authentication required" 

23 ) 

24 

25 if credentials.credentials not in config.API_TOKENS: 

26 raise HTTPException( 

27 status_code=status.HTTP_401_UNAUTHORIZED, 

28 detail="Invalid authentication token" 

29 ) 

30 

31 return credentials.credentials 

32 

33 

34async def verify_ip(request: Request): 

35 """Verify IP whitelist""" 

36 if not config.ALLOWED_IPS: 

37 # No IP restriction 

38 return True 

39 

40 client_ip = request.client.host 

41 if client_ip not in config.ALLOWED_IPS: 

42 raise HTTPException( 

43 status_code=status.HTTP_403_FORBIDDEN, 

44 detail="IP not whitelisted" 

45 ) 

46 

47 return True