schema.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from datetime import datetime
  2. from typing import Optional
  3. from allauth.socialaccount.models import SocialAccount
  4. from ninja import Field, ModelSchema
  5. from glitchtip.schema import CamelSchema
  6. from .models import User
  7. class SocialAccountSchema(CamelSchema, ModelSchema):
  8. email: Optional[str]
  9. username: Optional[str]
  10. class Meta:
  11. model = SocialAccount
  12. fields = (
  13. "id",
  14. "provider",
  15. "uid",
  16. "last_login",
  17. "date_joined",
  18. )
  19. @staticmethod
  20. def resolve_email(obj):
  21. if obj.extra_data:
  22. if "email" in obj.extra_data:
  23. return obj.extra_data.get("email")
  24. return obj.extra_data.get("userPrincipalName") # MS oauth uses this
  25. @staticmethod
  26. def resolve_username(obj):
  27. if obj.extra_data:
  28. return obj.extra_data.get("username")
  29. class UserIn(CamelSchema, ModelSchema):
  30. class Meta:
  31. model = User
  32. fields = [
  33. "name",
  34. "options",
  35. ]
  36. class UserSchema(CamelSchema, ModelSchema):
  37. username: str = Field(validation_alias="email")
  38. created: datetime = Field(serialization_alias="dateJoined")
  39. has_password_auth: bool = Field(validation_alias="has_usable_password")
  40. identities: list[SocialAccountSchema] = Field(validation_alias="socialaccount_set")
  41. class Meta(UserIn.Meta):
  42. fields = [
  43. "last_login",
  44. "is_superuser",
  45. # "emails",
  46. "id",
  47. "is_active",
  48. "name",
  49. "email",
  50. "options",
  51. ]