main3.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from typing import Annotated
  2. from fastapi import Depends, FastAPI, HTTPException, status
  3. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  4. from pydantic import BaseModel
  5. fake_users_db = {
  6. "johndoe": {
  7. "username": "johndoe",
  8. "full_name": "John Doe",
  9. "email": "johndoe@example.com",
  10. "hashed_password": "fakehashedsecret",
  11. "disabled": False,
  12. },
  13. "alice": {
  14. "username": "alice",
  15. "full_name": "Alice Wonderson",
  16. "email": "alice@example.com",
  17. "hashed_password": "fakehashedsecret2",
  18. "disabled": True,
  19. },
  20. }
  21. app = FastAPI()
  22. def fake_hash_password(password: str):
  23. return "fakehashed" + password
  24. oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
  25. class User(BaseModel):
  26. username: str
  27. email: str | None = None
  28. full_name: str | None = None
  29. disabled: bool | None = None
  30. class UserInDB(User):
  31. hashed_password: str
  32. def get_user(db, username: str):
  33. if username in db:
  34. user_dict = db[username]
  35. return UserInDB(**user_dict)
  36. def fake_decode_token(token):
  37. # This doesn't provide any security at all
  38. # Check the next version
  39. user = get_user(fake_users_db, token)
  40. return user
  41. async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
  42. user = fake_decode_token(token)
  43. if not user:
  44. raise HTTPException(
  45. status_code=status.HTTP_401_UNAUTHORIZED,
  46. detail="Not authenticated",
  47. headers={"WWW-Authenticate": "Bearer"},
  48. )
  49. return user
  50. async def get_current_active_user(
  51. current_user: Annotated[User, Depends(get_current_user)],
  52. ):
  53. if current_user.disabled:
  54. raise HTTPException(status_code=400, detail="Inactive user")
  55. return current_user
  56. @app.post("/token")
  57. async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
  58. user_dict = fake_users_db.get(form_data.username)
  59. if not user_dict:
  60. raise HTTPException(status_code=400, detail="Incorrect username or password")
  61. user = UserInDB(**user_dict)
  62. hashed_password = fake_hash_password(form_data.password)
  63. if not hashed_password == user.hashed_password:
  64. raise HTTPException(status_code=400, detail="Incorrect username or password")
  65. return {"access_token": user.username, "token_type": "bearer"}
  66. @app.get("/users/me")
  67. async def read_users_me(
  68. current_user: Annotated[User, Depends(get_current_active_user)],
  69. ):
  70. return current_user