schema.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from datetime import datetime
  2. from typing import Optional
  3. from allauth.account.models import EmailAddress
  4. from allauth.socialaccount.models import SocialAccount
  5. from ninja import Field, ModelSchema
  6. from pydantic import EmailStr
  7. from glitchtip.schema import CamelSchema
  8. from .models import User
  9. class SocialAccountSchema(CamelSchema, ModelSchema):
  10. email: Optional[EmailStr]
  11. username: Optional[str]
  12. class Meta:
  13. model = SocialAccount
  14. fields = (
  15. "id",
  16. "provider",
  17. "uid",
  18. "last_login",
  19. "date_joined",
  20. )
  21. @staticmethod
  22. def resolve_email(obj):
  23. if obj.extra_data:
  24. if "email" in obj.extra_data:
  25. return obj.extra_data.get("email")
  26. return obj.extra_data.get("userPrincipalName") # MS oauth uses this
  27. @staticmethod
  28. def resolve_username(obj):
  29. if obj.extra_data:
  30. return obj.extra_data.get("username")
  31. class UserIn(CamelSchema, ModelSchema):
  32. class Meta:
  33. model = User
  34. fields = [
  35. "name",
  36. "options",
  37. ]
  38. class UserSchema(CamelSchema, ModelSchema):
  39. username: EmailStr = Field(validation_alias="email")
  40. created: datetime = Field(serialization_alias="dateJoined")
  41. email: EmailStr
  42. has_password_auth: bool = Field(validation_alias="has_usable_password")
  43. identities: list[SocialAccountSchema] = Field(validation_alias="socialaccount_set")
  44. class Meta(UserIn.Meta):
  45. fields = [
  46. "last_login",
  47. "is_superuser",
  48. # "emails",
  49. "id",
  50. "is_active",
  51. "name",
  52. "email",
  53. "options",
  54. ]
  55. class EmailAddressIn(CamelSchema, ModelSchema):
  56. email: EmailStr
  57. class Meta:
  58. model = EmailAddress
  59. fields = ["email"]
  60. class EmailAddressSchema(CamelSchema, ModelSchema):
  61. isPrimary: bool = Field(validation_alias="primary")
  62. isVerified: bool = Field(validation_alias="verified")
  63. class Meta(EmailAddressIn.Meta):
  64. pass
  65. class UserNotificationsSchema(CamelSchema, ModelSchema):
  66. class Meta:
  67. model = User
  68. fields = ("subscribe_by_default",)