Skip to content

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

Apply changes after review

Maciej Korycinski7ab7eb1e9ba5
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 56f6d7e624..6d1b8617b9 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -221,12 +221,12 @@ class ServiceAccount(ModelWithMetadata):
def has_perms(self, perm_list):
"""Return True if the service has each of the specified permissions."""
- wanted_perms = set(perm_list)
- actual_perms = self._get_permissions()
-
if not self.is_active:
return False
+ wanted_perms = set(perm_list)
+ actual_perms = self._get_permissions()
+
return (wanted_perms & actual_perms) == wanted_perms
def has_perm(self, perm):
diff --git a/saleor/graphql/account/mutations/service_account.py b/saleor/graphql/account/mutations/service_account.py
index 17a55a1e84..90bbcd1631 100644
--- a/saleor/graphql/account/mutations/service_account.py
+++ b/saleor/graphql/account/mutations/service_account.py
@@ -15,7 +15,7 @@ from ...core.mutations import (
class ServiceAccountInput(graphene.InputObjectType):
name = graphene.types.String(description="Name of the service account")
is_active = graphene.types.Boolean(
- description="Determine if service account should be enabled"
+ description="Determine if this service account should be enabled"
)
permissions = graphene.List(
PermissionEnum,
@@ -82,8 +82,7 @@ class ServiceAccountUpdate(ModelMutation):
cleaned_input = super().clean_input(info, instance, data)
# clean and prepare permissions
if "permissions" in cleaned_input:
- permissions = cleaned_input.pop("permissions")
- cleaned_input["permissions"] = get_permissions(permissions)
+ cleaned_input["permissions"] = get_permissions(cleaned_input["permissions"])
return cleaned_input
@@ -101,7 +100,7 @@ class ServiceAccountDelete(ModelDeleteMutation):
class ServiceAccountUpdatePrivateMeta(UpdateMetaBaseMutation):
class Meta:
- description = "Updates private metadata for service account."
+ description = "Updates private metadata for a service account."
permissions = ("account.manage_service_account",)
model = models.ServiceAccount
public = False
diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.py
index 972a17f452..a6d0798e2e 100644
--- a/saleor/graphql/account/schema.py
+++ b/saleor/graphql/account/schema.py
@@ -112,7 +112,7 @@ class AccountQueries(graphene.ObjectType):
description="Lookup a service account by ID.",
)
service_account_valid_token = graphene.Field(
- graphene.Boolean, description="Confirm token for service account"
+ graphene.Boolean, description="Confirm token for a service account"
)
user = graphene.Field(
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 44b28c446a..00491e87cb 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -156,11 +156,12 @@ class CustomerEvent(CountableDjangoObjectType):
class ServiceAccount(MetadataObjectType, CountableDjangoObjectType):
permissions = graphene.List(
- PermissionDisplay, description="List of service's permissions."
+ PermissionDisplay, description="List of the service's permissions."
)
created = graphene.DateTime(description="Created date")
is_active = graphene.Boolean()
name = graphene.String()
+ auth_token = graphene.String(description="Last 4 characters of the token")
class Meta:
description = "Represents service account data."
@@ -178,11 +179,11 @@ class ServiceAccount(MetadataObjectType, CountableDjangoObjectType):
@staticmethod
def resolve_auth_token(root: models.ServiceAccount, _info, **_kwargs):
- return "*" * 6 + root.auth_token[-4:]
+ return root.auth_token[-4:]
@staticmethod
- def resolve_meta(root, _info):
- return resolve_meta(root, _info)
+ def resolve_meta(root, info):
+ return resolve_meta(root, info)
class User(MetadataObjectType, CountableDjangoObjectType):
diff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.py
index 666f436911..5e475d3f53 100644
--- a/saleor/graphql/decorators.py
+++ b/saleor/graphql/decorators.py
@@ -5,7 +5,9 @@ from graphql_jwt import exceptions
from graphql_jwt.decorators import context
-def user_passes_test(test_func):
+def account_passes_test(test_func):
+ """Determine if user/service_account has permission to access to content."""
+
def decorator(f):
@wraps(f)
@context(f)
@@ -32,4 +34,4 @@ def permission_required(perm):
return True
return False
- return user_passes_test(check_perms)
+ return account_passes_test(check_perms)
diff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.py
index c8e294a363..b2708e08b6 100644
--- a/saleor/graphql/middleware.py
+++ b/saleor/graphql/middleware.py
@@ -1,10 +1,12 @@
+from typing import Optional
+
from django.contrib.auth.models import AnonymousUser
from django.shortcuts import reverse
from django.utils.functional import SimpleLazyObject
from graphene_django.settings import graphene_settings
from graphql_jwt.middleware import JSONWebTokenMiddleware
-from saleor.account.models import ServiceAccount
+from ..account.models import ServiceAccount
def jwt_middleware(get_response):
@@ -32,7 +34,7 @@ def jwt_middleware(get_response):
return middleware
-def get_service_account(auth_token):
+def get_service_account(auth_token) -> Optional[ServiceAccount]:
qs = ServiceAccount.objects.filter(auth_token=auth_token, is_active=True)
return qs.first()
@@ -40,14 +42,14 @@ def get_service_account(auth_token):
def service_account_middleware(get_response):
service_account_auth_header = "HTTP_AUTHORIZATION"
- prefix = "Bearer"
+ prefix = "bearer"
def middleware(request):
if request.path == reverse("api"):
auth = request.META.get(service_account_auth_header, "").split()
if len(auth) == 2:
auth_prefix, auth_token = auth
- if auth_prefix == prefix:
+ if auth_prefix.lower() == prefix:
request.service = SimpleLazyObject(
lambda: get_service_account(auth_token)
)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 36d6f033fd..8fd5328c0b 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3103,7 +3103,7 @@ input SeoInput {
type ServiceAccount implements Node {
id: ID!
- authToken: String!
+ authToken: String
created: DateTime
isActive: Boolean
privateMeta: [MetaStore]!
diff --git a/tests/api/test_account_bot.py b/tests/api/test_account_bot.py
index 778e096604..774291df7e 100644
--- a/tests/api/test_account_bot.py
+++ b/tests/api/test_account_bot.py
@@ -126,9 +126,7 @@ def test_service_account_update_mutation(
assert service_account_data["isActive"] == service_account.is_active
assert service_account.is_active is False
- assert (
- service_account_data["authToken"] == "*" * 6 + service_account.auth_token[-4:]
- )
+ assert service_account_data["authToken"] == service_account.auth_token[-4:]
assert set(service_account.permissions.all()) == {
permission_manage_products,
permission_manage_users,
@@ -149,9 +147,7 @@ def test_service_account_update_no_permission(
assert_no_permission(response)
-def query_service_accounts_with_filter():
- query = """
+QUERY_SERVICE_ACCOUNTS_WITH_FILTER = """
query ($filter: ServiceAccountFilterInput ){
serviceAccounts(first: 5, filter: $filter){
edges{
@@ -169,7 +165,6 @@ def query_service_accounts_with_filter():
}
}
"""
- return query
@pytest.mark.parametrize(
@@ -177,7 +172,6 @@ def query_service_accounts_with_filter():
(({"search": "Sample"}, 1), ({"isActive": False}, 1), ({}, 2)),
)
def test_service_accounts_query(
- query_service_accounts_with_filter,
staff_api_client,
permission_manage_service_accounts,
service_account,
@@ -190,7 +184,7 @@ def test_service_accounts_query(
variables = {"filter": service_account_filter}
response = staff_api_client.post_graphql(
- query_service_accounts_with_filter,
+ QUERY_SERVICE_ACCOUNTS_WITH_FILTER,
variables,
permissions=[permission_manage_service_accounts],
)
@@ -199,35 +193,28 @@ def test_service_accounts_query(
service_accounts_data = content["data"]["serviceAccounts"]["edges"]
for service_account_data in service_accounts_data:
token = service_account_data["node"]["authToken"]
- assert token.startswith("*" * 6)
- assert len(token) == 10
+ assert len(token) == 4
assert len(service_accounts_data) == count
def test_service_accounts_query_no_permission(
- query_service_accounts_with_filter,
- staff_api_client,
- permission_manage_users,
- permission_manage_staff,
- service_account,
+ staff_api_client, permission_manage_users, permission_manage_staff, service_account
):
variables = {"filter": {}}
response = staff_api_client.post_graphql(
- query_service_accounts_with_filter, variables, permissions=[]
+ QUERY_SERVICE_ACCOUNTS_WITH_FILTER, variables, permissions=[]
)
assert_no_permission(response)
response = staff_api_client.post_graphql(
- query_service_accounts_with_filter,
+ QUERY_SERVICE_ACCOUNTS_WITH_FILTER,
variables,
permissions=[permission_manage_users, permission_manage_staff],
)
assert_no_permission(response)
-def query_service_account():
- query = """
+QUERY_SERVICE_ACCOUNT = """
query ($id: ID! ){
serviceAccount(id: $id){
id
@@ -242,11 +229,9 @@ def query_service_account():
}
}
"""
- return query
def test_service_account_query(
- query_service_account,
staff_api_client,
permission_manage_service_accounts,
permission_manage_staff,
@@ -257,16 +242,14 @@ def test_service_account_query(
id = graphene.Node.to_global_id("ServiceAccount", service_account.id)
variables = {"id": id}
response = staff_api_client.post_graphql(
- query_service_account,
+ QUERY_SERVICE_ACCOUNT,
variables,
permissions=[permission_manage_service_accounts],
)
content = get_graphql_content(response)
service_account_data = content["data"]["serviceAccount"]
- assert (
- service_account_data["authToken"] == "*" * 6 + service_account.auth_token[-4:]
- )
+ assert service_account_data["authToken"] == service_account.auth_token[-4:]
assert service_account_data["isActive"] == service_account.is_active
assert service_account_data["permissions"] == [
{"code": "MANAGE_STAFF", "name": "Manage staff."}
@@ -274,23 +257,19 @@ def test_service_account_query(
def test_service_account_query_no_permission(
- query_service_account,
- staff_api_client,
- permission_manage_staff,
- permission_manage_users,
- service_account,
+ staff_api_client, permission_manage_staff, permission_manage_users, service_account
):
service_account.permissions.add(permission_manage_staff)
id = graphene.Node.to_global_id("ServiceAccount", service_account.id)
variables = {"id": id}
response = staff_api_client.post_graphql(
- query_service_account, variables, permissions=[]
+ QUERY_SERVICE_ACCOUNT, variables, permissions=[]
)
assert_no_permission(response)
response = staff_api_client.post_graphql(
- query_service_account,
+ QUERY_SERVICE_ACCOUNT,
variables,
permissions=[permission_manage_users, permission_manage_staff],
)
@@ -321,44 +300,35 @@ def test_service_account_with_access_to_resources(
get_graphql_content(response)
-def query_service_account_valid_token():
- query = """
+QUERY_SERVICE_ACCOUNT_VALID_TOKEN = """
query {
serviceAccountValidToken
}
"""
- return query
-def test_service_account_valid_token(
- service_account_api_client, service_account, query_service_account_valid_token
-):
+def test_service_account_valid_token(service_account_api_client, service_account):
response = service_account_api_client.post_graphql(
- query_service_account_valid_token
+ QUERY_SERVICE_ACCOUNT_VALID_TOKEN
)
content = get_graphql_content(response)
valid_token = content["data"]["serviceAccountValidToken"]
assert valid_token
-def test_service_account_empty_token(
- service_account, query_service_account_valid_token
-):
+def test_service_account_empty_token(service_account):
api = ApiClient()
- response = api.post_graphql(query_service_account_valid_token)
+ response = api.post_graphql(QUERY_SERVICE_ACCOUNT_VALID_TOKEN)
content = get_graphql_content(response)
valid_token = content["data"]["serviceAccountValidToken"]
assert valid_token is False
-def test_service_account_invalid_token(
- service_account_api_client, service_account, query_service_account_valid_token
-):
+def test_service_account_invalid_token(service_account_api_client, service_account):
service_account.auth_token = "12345"
service_account.save()
response = service_account_api_client.post_graphql(
- query_service_account_valid_token
+ QUERY_SERVICE_ACCOUNT_VALID_TOKEN
)
content = get_graphql_content(response)
valid_token = content["data"]["serviceAccountValidToken"]
diff --git a/tests/api/test_middleware.py b/tests/api/test_middleware.py
index f176c970ef..7544b92fc0 100644
--- a/tests/api/test_middleware.py
+++ b/tests/api/test_middleware.py
@@ -6,8 +6,20 @@ from django.urls import reverse
from saleor.graphql.middleware import service_account_middleware
[email protected]("path, should_accept", [("api", True), ("home", False)])
-def test_service_account_middleware(service_account, path, should_accept, rf):
+def test_service_account_middleware_accepts_api_requests(service_account, rf):
+
+ # Retrieve sample request object
+ request = rf.get(reverse("api"))
+ request.META = {"HTTP_AUTHORIZATION": f"Bearer {service_account.auth_token}"}
+
+ middleware = service_account_middleware(Mock())
+ middleware(request)
+
+ assert request.service == service_account
+
+
[email protected]("path", ["account:details", "home"])
+def test_service_account_middleware_block(service_account, path, rf):
# Retrieve sample request object
request = rf.get(reverse("api"))
@@ -18,7 +30,4 @@ def test_service_account_middleware(service_account, path, should_accept, rf):
middleware = service_account_middleware(Mock())
middleware(request)
- if should_accept:
- assert request.service == service_account
- else:
- assert not hasattr(request, "service")
+ assert not hasattr(request, "service")