schema.py 6.2 KB

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