schema.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. if user.is_active:
  41. acl.append("active")
  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. password = None
  97. ava = None
  98. acl = []
  99. if "password" in user and len(user["password"]) < 3:
  100. raise Exception("Не вірні дані (пароль)")
  101. elif "password" in user:
  102. password = str(user.pop("password"))
  103. if "acl" in user:
  104. acl = user.get("acl", [])
  105. user.pop("acl")
  106. if "avatar" in user:
  107. if user.get("avatar") == "null":
  108. ava = user.pop("avatar")
  109. else:
  110. try:
  111. ava = Image.objects.get(_id = user.pop("avatar")["_id"])
  112. except:
  113. raise Exception("Не вірні дані (аватар)")
  114. try:
  115. _id = user._id
  116. new_user = User.objects.get(_id = _id)
  117. if not info.context.user.is_superuser:
  118. raise Exception("Authentication credentials were not provided")
  119. user.pop("_id",None)
  120. new_user.__dict__.update(**user)
  121. if password:
  122. new_user.set_password(password)
  123. except Exception as e:
  124. if info.context.user.is_authenticated:
  125. try:
  126. new_user = User.objects.get(username = info.context.user.username)
  127. new_user.__dict__.update(**user)
  128. if password:
  129. new_user.set_password(password)
  130. except:
  131. raise Exception("Не вірні дані")
  132. else:
  133. try:
  134. User.objects.get(username = user.username)
  135. raise Exception("Username вже зайнятий")
  136. except:
  137. pass
  138. new_user = User.objects.create_user(username = user.username,password=user.password)
  139. if ava:
  140. if ava == "null":
  141. new_user.avatar = None
  142. else:
  143. new_user.avatar = ava
  144. if len(acl):
  145. if not info.context.user.is_superuser:
  146. raise Exception("Authentication credentials were not provided")
  147. new_user.is_active = "active" in acl
  148. new_user.is_superuser = "admin" in acl
  149. new_user.save()
  150. user_data = {key: new_user.__dict__[key] for key in new_user.__dict__.keys() & {"username","_id","name","avatar","nick"}}
  151. user_data["_id"] = new_user._id
  152. return UserType(**user_data)
  153. # class GoodDelete(graphene.Mutation):
  154. # class Arguments:
  155. # good = GoodInput(required=True)
  156. # Output =GoodType
  157. # @staticmethod
  158. # def mutate(root,info,good):
  159. # user = info.context.user
  160. # if not user.is_superuser:
  161. # raise Exception("Authentication credentials were not provided")
  162. # try:
  163. # _id = good._id
  164. # good_to_delete = Good.objects.get(_id=_id)
  165. # good_data = model_to_dict(good_to_delete)
  166. # good_data["_id"] = new_good._id
  167. # good_to_delete.delete()
  168. # except:
  169. # raise Exception("Не вірні дані")
  170. # return GoodType(**good_data)
  171. class Mutations(graphene.ObjectType):
  172. token_auth = graphql_jwt.ObtainJSONWebToken.Field()
  173. verify_token = graphql_jwt.Verify.Field()
  174. refresh_token = graphql_jwt.Refresh.Field()
  175. UserUpsert = UserUpsert.Field()
  176. # GoodDelete = GoodDelete.Field()