schema.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. print(query_set)
  71. query_set = query_set.order_by(order_by)[skip:skip+limit]
  72. return query_set
  73. def resolve_UserFindOne(self,info,query = "[{}]"):
  74. user = info.context.user
  75. additional_params = {}
  76. query_list = json.loads(query)
  77. filter_params = query_list[0]
  78. if len(query_list) > 1:
  79. additional_params = query_list[1]
  80. skip = additional_params.get("skip",0)
  81. limit = additional_params.get("limit",20)
  82. order_by = additional_params.get("orderBy","_id")
  83. if user.is_superuser:
  84. query_set = User.objects.all()
  85. else:
  86. query_set = User.objects.filter(pk=user._id)
  87. if len(filter_params):
  88. query_set = query_set.filter(reduce(operator.and_,(Q(**d) for d in [dict([i]) for i in filter_params.items()])))
  89. return query_set.first()
  90. class UserUpsert(graphene.Mutation):
  91. class Arguments:
  92. user = UserInput(required=True)
  93. Output =UserType
  94. @staticmethod
  95. def mutate(root,info,user):
  96. new_user={}
  97. password = None
  98. ava = None
  99. acl = []
  100. if "password" in user and len(user["password"]) < 3:
  101. raise Exception("Не вірні дані (пароль)")
  102. elif "password" in user:
  103. password = str(user.pop("password"))
  104. if "acl" in user:
  105. acl = user.get("acl", [])
  106. user.pop("acl")
  107. if "avatar" in user:
  108. if user.get("avatar") == "null":
  109. ava = user.pop("avatar")
  110. else:
  111. try:
  112. ava = Image.objects.get(_id = user.pop("avatar")["_id"])
  113. except:
  114. raise Exception("Не вірні дані (аватар)")
  115. try:
  116. _id = user._id
  117. new_user = User.objects.get(_id = _id)
  118. if not info.context.user.is_superuser:
  119. raise Exception("Authentication credentials were not provided")
  120. user.pop("_id",None)
  121. new_user.__dict__.update(**user)
  122. if password:
  123. new_user.set_password(password)
  124. except Exception as e:
  125. if info.context.user.is_authenticated:
  126. try:
  127. new_user = User.objects.get(username = info.context.user.username)
  128. new_user.__dict__.update(**user)
  129. if password:
  130. new_user.set_password(password)
  131. except:
  132. raise Exception("Не вірні дані")
  133. else:
  134. try:
  135. User.objects.get(username = user.username)
  136. raise Exception("Username вже зайнятий")
  137. except:
  138. pass
  139. new_user = User.objects.create_user(username = user.username,password=user.password)
  140. if ava:
  141. if ava == "null":
  142. new_user.avatar = None
  143. else:
  144. new_user.avatar = ava
  145. if len(acl):
  146. if not info.context.user.is_superuser:
  147. raise Exception("Authentication credentials were not provided")
  148. new_user.is_active = "active" in acl
  149. new_user.is_superuser = "admin" in acl
  150. new_user.save()
  151. user_data = {key: new_user.__dict__[key] for key in new_user.__dict__.keys() & {"username","_id","name","avatar","nick"}}
  152. user_data["_id"] = new_user._id
  153. return UserType(**user_data)
  154. class Mutations(graphene.ObjectType):
  155. token_auth = graphql_jwt.ObtainJSONWebToken.Field()
  156. verify_token = graphql_jwt.Verify.Field()
  157. refresh_token = graphql_jwt.Refresh.Field()
  158. UserUpsert = UserUpsert.Field()