schema.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import graphene
  2. from graphene_django.types import DjangoObjectType
  3. from graphql_jwt.decorators import login_required
  4. from goods.schema import ImageType,ImageInput
  5. import json
  6. from functools import reduce
  7. from django.forms.models import model_to_dict
  8. from django.contrib.auth import get_user_model
  9. from goods.models import Image
  10. import operator
  11. from django.db.models import Q
  12. import graphene
  13. import graphql_jwt
  14. User = get_user_model()
  15. class UserType(graphene.ObjectType):
  16. _id = graphene.String(name='_id')
  17. avatar = graphene.Field(ImageType)
  18. name = graphene.String()
  19. nick = graphene.String()
  20. username = graphene.String()
  21. acl = graphene.List(graphene.String)
  22. createdAt = graphene.String()
  23. def resolve__id(self,info):
  24. return self._id
  25. def resolve_avatar(self,info):
  26. return self.avatar
  27. def resolve_nick(self,info):
  28. return self.nick
  29. def resolve_name(self,info):
  30. return self.name
  31. def resolve_username(self,info):
  32. return self.username
  33. def resolve_acl(self,info):
  34. user = User.objects.get(_id = self._id)
  35. acl = ["anon"]
  36. if user._id:
  37. acl.append(str(user._id))
  38. acl.append("user")
  39. if user.is_superuser:
  40. acl.append("admin")
  41. return acl
  42. def resolve_createdAt(self,info):
  43. return self.createdAt.strftime('%s')
  44. class UserInput(graphene.InputObjectType):
  45. _id = graphene.String(name='_id')
  46. avatar = graphene.Field(ImageInput)
  47. name = graphene.String()
  48. nick = graphene.String()
  49. acl = graphene.List(graphene.String)
  50. username = graphene.String()
  51. password = graphene.String()
  52. class Query(graphene.ObjectType):
  53. UserFind = graphene.List(UserType,query = graphene.String())
  54. UserFindOne = graphene.Field(UserType,query = graphene.String())
  55. def resolve_UserFind(self,info,query = "[{}]"):
  56. additional_params = {}
  57. query_list = json.loads(query)
  58. filter_params = query_list[0]
  59. if len(query_list) > 1:
  60. additional_params = query_list[1]
  61. skip = int(additional_params.get("skip",0))
  62. limit = int(additional_params.get("limit",20))
  63. order_by = additional_params.get("orderBy","_id")
  64. query_set = User.objects.all()
  65. if len(filter_params):
  66. query_set = query_set.filter(reduce(operator.or_,(Q(**d) for d in [dict([i]) for i in filter_params.items()])))
  67. query_set = query_set.order_by(order_by)[skip:skip+limit]
  68. return query_set
  69. def resolve_UserFindOne(self,info,query = "[{}]"):
  70. additional_params = {}
  71. query_list = json.loads(query)
  72. filter_params = query_list[0]
  73. if len(query_list) > 1:
  74. additional_params = query_list[1]
  75. skip = additional_params.get("skip",0)
  76. limit = additional_params.get("limit",20)
  77. order_by = additional_params.get("orderBy","_id")
  78. query_set = User.objects.all()
  79. if len(filter_params):
  80. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in filter_params.items()])))
  81. return query_set.first()
  82. class UserUpsert(graphene.Mutation):
  83. class Arguments:
  84. user = UserInput(required=True)
  85. Output =UserType
  86. @staticmethod
  87. def mutate(root,info,user):
  88. new_user={}
  89. ava = None
  90. if "avatar" in user:
  91. if user.get("avatar") == "null":
  92. ava = user.pop("avatar")
  93. else:
  94. try:
  95. ava = Image.objects.get(_id = user.pop("avatar")["_id"])
  96. except:
  97. raise Exception("Не вірні дані (аватар)")
  98. print(ava)
  99. try:
  100. _id = user._id
  101. new_user = User.objects.get(_id = _id)
  102. if not info.context.user.is_superuser:
  103. raise Exception("Authentication credentials were not provided")
  104. user.pop("_id",None)
  105. new_user.__dict__.update(**user)
  106. except Exception as e:
  107. if info.context.user.is_authenticated:
  108. try:
  109. new_user = User.objects.get(_id = info.context.user._id)
  110. new_user.__dict__.update(**user)
  111. except:
  112. raise Exception("Не вірні дані")
  113. else:
  114. try:
  115. User.objects.get(username = user.username)
  116. raise Exception("Username вже зайнятий")
  117. except:
  118. pass
  119. new_user = User.objects.create_user(username = user.username,password=user.password)
  120. if ava:
  121. if ava == "null":
  122. print(1)
  123. new_user.avatar = None
  124. else:
  125. print(2)
  126. new_user.avatar = ava
  127. new_user.save()
  128. print(new_user)
  129. user_data = {key: new_user.__dict__[key] for key in new_user.__dict__.keys() & {"username","_id","name","avatar","nick"}}
  130. user_data["_id"] = new_user._id
  131. return UserType(**user_data)
  132. # class GoodDelete(graphene.Mutation):
  133. # class Arguments:
  134. # good = GoodInput(required=True)
  135. # Output =GoodType
  136. # @staticmethod
  137. # def mutate(root,info,good):
  138. # user = info.context.user
  139. # if not user.is_superuser:
  140. # raise Exception("Authentication credentials were not provided")
  141. # try:
  142. # _id = good._id
  143. # good_to_delete = Good.objects.get(_id=_id)
  144. # good_data = model_to_dict(good_to_delete)
  145. # good_data["_id"] = new_good._id
  146. # good_to_delete.delete()
  147. # except:
  148. # raise Exception("Не вірні дані")
  149. # return GoodType(**good_data)
  150. class Mutations(graphene.ObjectType):
  151. token_auth = graphql_jwt.ObtainJSONWebToken.Field()
  152. verify_token = graphql_jwt.Verify.Field()
  153. refresh_token = graphql_jwt.Refresh.Field()
  154. UserUpsert = UserUpsert.Field()
  155. # GoodDelete = GoodDelete.Field()