Coverage for docs_src / security / tutorial007_py310.py: 100%

18 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1import secrets 1def

2 

3from fastapi import Depends, FastAPI, HTTPException, status 1def

4from fastapi.security import HTTPBasic, HTTPBasicCredentials 1def

5 

6app = FastAPI() 1def

7 

8security = HTTPBasic() 1def

9 

10 

11def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): 1def

12 current_username_bytes = credentials.username.encode("utf8") 1aghbijckl

13 correct_username_bytes = b"stanleyjobson" 1aghbijckl

14 is_correct_username = secrets.compare_digest( 1aghbijckl

15 current_username_bytes, correct_username_bytes 

16 ) 

17 current_password_bytes = credentials.password.encode("utf8") 1aghbijckl

18 correct_password_bytes = b"swordfish" 1aghbijckl

19 is_correct_password = secrets.compare_digest( 1aghbijckl

20 current_password_bytes, correct_password_bytes 

21 ) 

22 if not (is_correct_username and is_correct_password): 1aghbijckl

23 raise HTTPException( 1ghijkl

24 status_code=status.HTTP_401_UNAUTHORIZED, 

25 detail="Incorrect username or password", 

26 headers={"WWW-Authenticate": "Basic"}, 

27 ) 

28 return credentials.username 1abc

29 

30 

31@app.get("/users/me") 1def

32def read_current_user(username: str = Depends(get_current_username)): 1def

33 return {"username": username} 1abc