Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Separate queries for staff and customers; fix SetPassword mutation

Marcin Gębala3855aa360515
diff --git a/saleor/account/models.py b/saleor/account/models.py
index da46dd9b91..e2ec186225 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -97,6 +97,9 @@ class UserManager(BaseUserManager):
return self.get_queryset().filter(
Q(is_staff=False) | (Q(is_staff=True) & Q(orders__isnull=False)))
+ def staff(self):
+ return self.get_queryset().filter(is_staff=True)
+
def get_token():
return str(uuid.uuid4())
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.py
index 2d3a5bedc8..3ba148101c 100644
--- a/saleor/graphql/account/mutations.py
+++ b/saleor/graphql/account/mutations.py
@@ -1,4 +1,5 @@
import graphene
+from django.contrib.auth.tokens import default_token_generator
from ...account import models
from ...core.permissions import get_permissions, MODELS_PERMISSIONS
@@ -23,7 +24,8 @@ class StaffInput(UserInput):
class CustomerCreate(ModelMutation):
class Arguments:
- input = UserInput()
+ input = UserInput(
+ description='Fields required to create a customer.', required=True)
class Meta:
description = 'Creates a new customer.'
@@ -37,8 +39,10 @@ class CustomerCreate(ModelMutation):
class CustomerUpdate(CustomerCreate):
class Arguments:
- id = graphene.ID()
- input = UserInput()
+ id = graphene.ID(
+ description='ID of a customer to update.', required=True)
+ input = UserInput(
+ description='Fields required to update a customer.', required=True)
class Meta:
description = 'Updates an existing customer.'
@@ -48,7 +52,9 @@ class CustomerUpdate(CustomerCreate):
class StaffCreate(ModelMutation):
class Arguments:
- input = StaffInput()
+ input = StaffInput(
+ description='Fields required to create a staff user.',
+ required=True)
class Meta:
description = 'Creates a new staff user.'
@@ -63,6 +69,10 @@ class StaffCreate(ModelMutation):
def clean_input(cls, info, instance, input, errors):
cleaned_input = super().clean_input(info, instance, input, errors)
+ # set is_staff to True to create a staff user
+ cleaned_input['is_staff'] = True
+
+ # clean and prepare permissions
if 'permissions' in cleaned_input:
permissions = cleaned_input['permissions']
cleaned_permissions = []
@@ -80,8 +90,11 @@ class StaffCreate(ModelMutation):
class StaffUpdate(StaffCreate):
class Arguments:
- id = graphene.ID()
- input = StaffInput()
+ id = graphene.ID(
+ description='ID of a staff user to update.', required=True)
+ input = StaffInput(
+ description='Fields required to update a staff user.',
+ required=True)
class Meta:
description = 'Updates an existing staff user.'
@@ -91,14 +104,17 @@ class StaffUpdate(StaffCreate):
class SetPasswordInput(graphene.InputObjectType):
token = graphene.String(
- description='A one-time token required to set the password.')
- password = graphene.String(description='Password')
+ description='A one-time token required to set the password.',
+ required=True)
+ password = graphene.String(description='Password', required=True)
class SetPassword(ModelMutation):
class Arguments:
- id = graphene.ID()
- input = SetPasswordInput()
+ id = graphene.ID(
+ description='ID of a user to set password whom.', required=True)
+ input = SetPasswordInput(
+ description='Fields required to set password.', required=True)
class Meta:
description = 'Sets user password.'
@@ -107,8 +123,12 @@ class SetPassword(ModelMutation):
@classmethod
def clean_input(cls, info, instance, input, errors):
cleaned_input = super().clean_input(info, instance, input, errors)
- cleaned_input.pop('token')
+ token = cleaned_input.pop('token')
+ if not default_token_generator.check_token(instance, token):
+ cls.add_error(errors, 'token', 'Invalid or expired token.')
return cleaned_input
- # FIXME: make sure about the permissions. At the moment any user with
- # valid token can set the password.
+ @classmethod
+ def save(cls, instance, cleaned_input):
+ instance.set_password(cleaned_input['password'])
+ instance.save()
diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.py
index 86dc9a1a49..a6f49f6161 100644
--- a/saleor/graphql/account/resolvers.py
+++ b/saleor/graphql/account/resolvers.py
@@ -6,24 +6,38 @@ from ..utils import filter_by_query_param, get_node
from .types import User
-USER_SEARCH_FIELDS = (
+CUSTOMER_SEARCH_FIELDS = (
'email', 'default_shipping_address__first_name',
'default_shipping_address__last_name', 'default_shipping_address__city',
'default_shipping_address__country')
+STAFF_SEARCH_FIELDS = ('email',)
GROUP_SEARCH_FIELDS = ('name', )
+# @staff_member_required
+def resolve_staff_users(info, query):
+ qs = models.User.objects.staff()
+ return filter_by_query_param(qs, query, STAFF_SEARCH_FIELDS)
+
+
+@staff_member_required
+def resolve_staff_user(info, id):
+ # FIXME: lookup node in staff users only
+ return get_node(info, id, only_type=User)
+
+
@permission_required(['account.view_user', 'account.edit_user'])
-def resolve_users(info, query):
- qs = models.User.objects.all().prefetch_related('addresses')
+def resolve_customers(info, query):
+ qs = models.User.objects.customers().prefetch_related('addresses')
return filter_by_query_param(
- queryset=qs, query=query, search_fields=USER_SEARCH_FIELDS)
+ queryset=qs, query=query, search_fields=CUSTOMER_SEARCH_FIELDS)
@permission_required(['account.view_user', 'account.edit_user'])
-def resolve_user(info, id):
+def resolve_customer(info, id):
+ # FIXME: lookup node in customers only
return get_node(info, id, only_type=User)
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index c214bf1921..c305715d27 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -5,8 +5,10 @@ from graphene_django.filter import DjangoFilterConnectionField
from graphql_jwt.decorators import permission_required
from .account.mutations import (
- CustomerCreate, CustomerUpdate, StaffCreate, StaffUpdate)
-from .account.resolvers import resolve_groups, resolve_user, resolve_users
+ CustomerCreate, CustomerUpdate, SetPassword, StaffCreate, StaffUpdate)
+from .account.resolvers import (
+ resolve_customer, resolve_customers, resolve_groups, resolve_staff_user,
+ resolve_staff_users)
from .account.types import Group, User
from .descriptions import DESCRIPTIONS
from .discount.resolvers import resolve_sales, resolve_vouchers
@@ -61,6 +63,13 @@ class Query(graphene.ObjectType):
Collection, query=graphene.String(
description=DESCRIPTIONS['collection']),
description='List of the shop\'s collections.')
+ customer = graphene.Field(
+ User, id=graphene.Argument(graphene.ID),
+ description='Lookup a customer by ID.')
+ customers = DjangoFilterConnectionField(
+ User, description='List of the shop\'s customers.',
+ query=graphene.String(
+ description=DESCRIPTIONS['customer']))
groups = DjangoConnectionField(
Group, query=graphene.String(description=DESCRIPTIONS['group']),
description='List of shop\'s permission groups.')
@@ -100,6 +109,13 @@ class Query(graphene.ObjectType):
shop = graphene.Field(
Shop, description='Represents a shop resources.',
resolver=resolve_shop)
+ staff_user = graphene.Field(
+ User, id=graphene.Argument(graphene.ID),
+ description='Lookup a staff user by ID.')
+ staff_users = DjangoFilterConnectionField(
+ User, description='List of the shop\'s staff users.',
+ query=graphene.String(
+ description=DESCRIPTIONS['staff']))
voucher = graphene.Field(
Voucher, id=graphene.Argument(graphene.ID),
description='Lookup a voucher by ID.')
@@ -111,13 +127,6 @@ class Query(graphene.ObjectType):
description='Lookup a shipping method by ID.')
shipping_methods = DjangoFilterConnectionField(
ShippingMethod, description='List of the shop\'s shipping methods.')
- user = graphene.Field(
- User, id=graphene.Argument(graphene.ID),
- description='Lookup an user type by ID.')
- users = DjangoFilterConnectionField(
- User, description='List of the shop\'s users.',
- query=graphene.String(
- description=DESCRIPTIONS['user']))
node = graphene.Node.Field()
def resolve_attributes(self, info, in_category=None, query=None, **kwargs):
@@ -135,6 +144,12 @@ class Query(graphene.ObjectType):
def resolve_collections(self, info, query=None, **kwargs):
resolve_collections(info, query)
+ def resolve_customer(self, info, id):
+ return resolve_customer(info, id)
+
+ def resolve_customers(self, info, query=None, **kwargs):
+ return resolve_customers(info, query=query)
+
def resolve_groups(self, info, query=None, **kwargs):
return resolve_groups(info, query)
@@ -184,11 +199,11 @@ class Query(graphene.ObjectType):
def resolve_shipping_methods(self, info, **kwargs):
return resolve_shipping_methods(info)
- def resolve_user(self, info, id):
- return resolve_user(info, id)
+ def resolve_staff_user(self, info, id):
+ return resolve_staff_user(info, id)
- def resolve_users(self, info, query=None, **kwargs):
- return resolve_users(info, query=query)
+ def resolve_staff_users(self, info, query=None, **kwargs):
+ return resolve_staff_users(info, query=query)
class Mutations(graphene.ObjectType):
@@ -196,6 +211,8 @@ class Mutations(graphene.ObjectType):
token_refresh = graphql_jwt.Refresh.Field()
token_verify = VerifyToken.Field()
+ set_password = SetPassword.Field()
+
category_create = CategoryCreateMutation.Field()
category_delete = CategoryDelete.Field()
category_update = CategoryUpdateMutation.Field()
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 569e6a019d..04e52d35b4 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -61,6 +61,9 @@ class ModelMutation(BaseMutation):
if not _meta:
_meta = ModelMutationOptions(cls)
+ if exclude is None:
+ exclude = []
+
return_field_name = get_model_name(model)
if arguments is None:
arguments = {}
@@ -165,6 +168,7 @@ class ModelMutation(BaseMutation):
model fields' validation. Returns errors ready to be returned by
the GraphQL response (if any occured).
"""
+ print(instance.__dict__)
try:
instance.full_clean()
except ValidationError as validation_errors:
@@ -201,6 +205,10 @@ class ModelMutation(BaseMutation):
"""Return a success response."""
return cls(**{cls._meta.return_field_name: instance, 'errors': []})
+ @classmethod
+ def save(cls, instance, cleaned_input):
+ instance.save()
+
@classmethod
def mutate(cls, root, info, **data):
"""Perform model mutation.
@@ -233,7 +241,7 @@ class ModelMutation(BaseMutation):
if errors:
return cls(errors=errors)
- instance.save()
+ cls.save(instance, cleaned_input)
cls._save_m2m(instance, cleaned_input)
return cls.success_response(instance)
diff --git a/saleor/graphql/descriptions.py b/saleor/graphql/descriptions.py
index e65c859967..4163f8dfe0 100644
--- a/saleor/graphql/descriptions.py
+++ b/saleor/graphql/descriptions.py
@@ -1,4 +1,5 @@
-from .account.resolvers import GROUP_SEARCH_FIELDS, USER_SEARCH_FIELDS
+from .account.resolvers import (
+ CUSTOMER_SEARCH_FIELDS, GROUP_SEARCH_FIELDS, STAFF_SEARCH_FIELDS)
from .discount.resolvers import SALE_SEARCH_FIELDS, VOUCHER_SEARCH_FIELDS
from .order.resolvers import ORDER_SEARCH_FIELDS
from .page.resolvers import PAGE_SEARCH_FIELDS
@@ -14,10 +15,11 @@ DESCRIPTIONS = {
'category': generate_query_argument_description(CATEGORY_SEARCH_FIELDS),
'collection': generate_query_argument_description(
COLLECTION_SEARCH_FIELDS),
+ 'customer': generate_query_argument_description(CUSTOMER_SEARCH_FIELDS),
'group': generate_query_argument_description(GROUP_SEARCH_FIELDS),
'order': generate_query_argument_description(ORDER_SEARCH_FIELDS),
'page': generate_query_argument_description(PAGE_SEARCH_FIELDS),
'product': generate_query_argument_description(PRODUCT_SEARCH_FIELDS),
'voucher': generate_query_argument_description(VOUCHER_SEARCH_FIELDS),
'sale': generate_query_argument_description(SALE_SEARCH_FIELDS),
- 'user': generate_query_argument_description(USER_SEARCH_FIELDS)}
+ 'staff': generate_query_argument_description(STAFF_SEARCH_FIELDS)}