Debian Codegraph @

docs_src/security/tutorial007_py310.py

raw
1 import secrets
2
3 from fastapi import Depends, FastAPI, HTTPException, status
4 from fastapi.security import HTTPBasic, HTTPBasicCredentials
5
6 app = FastAPI()
7
8 security = HTTPBasic()
9
10
11 def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
12 current_username_bytes = credentials.username.encode("utf8")
13 correct_username_bytes = b"stanleyjobson"
14 is_correct_username = secrets.compare_digest(
15 current_username_bytes, correct_username_bytes
16 )
17 current_password_bytes = credentials.password.encode("utf8")
18 correct_password_bytes = b"swordfish"
19 is_correct_password = secrets.compare_digest(
20 current_password_bytes, correct_password_bytes
21 )
22 if not (is_correct_username and is_correct_password):
23 raise HTTPException(
24 status_code=status.HTTP_401_UNAUTHORIZED,
25 detail="Incorrect username or password",
26 headers={"WWW-Authenticate": "Basic"},
27 )
28 return credentials.username
29
30
31 @app.get("/users/me")
32 def read_current_user(username: str = Depends(get_current_username)):
33 return {"username": username}