user.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from app import crud
  2. from app.core.config import settings
  3. from app.models import User, UserCreate, UserUpdate
  4. from app.tests.utils.utils import random_email, random_lower_string
  5. from sqlmodel import Session
  6. from fastapi.testclient import TestClient
  7. def user_authentication_headers(
  8. *, client: TestClient, email: str, password: str
  9. ) -> dict[str, str]:
  10. data = {"username": email, "password": password}
  11. r = client.post(f"{settings.API_V1_STR}/login/access-token", data=data)
  12. response = r.json()
  13. auth_token = response["access_token"]
  14. headers = {"Authorization": f"Bearer {auth_token}"}
  15. return headers
  16. def create_random_user(db: Session) -> User:
  17. email = random_email()
  18. password = random_lower_string()
  19. user_in = UserCreate(email=email, password=password)
  20. user = crud.create_user(session=db, user_create=user_in)
  21. return user
  22. def authentication_token_from_email(
  23. *, client: TestClient, email: str, db: Session
  24. ) -> dict[str, str]:
  25. """
  26. Return a valid token for the user with given email.
  27. If the user doesn't exist it is created first.
  28. """
  29. password = random_lower_string()
  30. user = crud.get_user_by_email(session=db, email=email)
  31. if not user:
  32. user_in_create = UserCreate(email=email, password=password)
  33. user = crud.create_user(session=db, user_create=user_in_create)
  34. else:
  35. user_in_update = UserUpdate(password=password)
  36. if not user.id:
  37. raise Exception("User id not set")
  38. user = crud.update_user(session=db, db_user=user, user_in=user_in_update)
  39. return user_authentication_headers(client=client, email=email, password=password)