schema.py 6.4 KB

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