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