Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add interface for integrating the auth plugins
Maciej Korycinski1985f88d6d0e
diff --git a/saleor/core/auth_backend.py b/saleor/core/auth_backend.pyindex f9f587f5c1..57f9dfa83b 100644--- a/saleor/core/auth_backend.py+++ b/saleor/core/auth_backend.py@@ -45,3 +45,10 @@ class JSONWebTokenBackend(ModelBackend):user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms})return getattr(user_obj, perm_cache_name)+++class PluginBackend(JSONWebTokenBackend):+ def authenticate(self, request=None, **kwargs):+ if request is None:+ return None+ return request.plugins.authenticate_user(request)diff --git a/saleor/core/jwt.py b/saleor/core/jwt.pyindex 19bf75a789..48537ce0fd 100644--- a/saleor/core/jwt.py+++ b/saleor/core/jwt.py@@ -8,7 +8,11 @@ from django.core.handlers.wsgi import WSGIRequestfrom ..account.models import Userfrom ..app.models import App-from .permissions import get_permission_names, get_permissions_from_names+from .permissions import (+ get_permission_names,+ get_permissions_from_codenames,+ get_permissions_from_names,+)JWT_ALGORITHM = "HS256"JWT_AUTH_HEADER = "HTTP_AUTHORIZATION"@@ -19,22 +23,29 @@ JWT_THIRDPARTY_ACCESS_TYPE = "thirdparty"JWT_REFRESH_TOKEN_COOKIE_NAME = "refreshToken"PERMISSIONS_FIELD = "permissions"+JWT_SALEOR_OWNER_NAME = "saleor"+JWT_OWNER_FIELD = "owner"-def jwt_base_payload(exp_delta: timedelta) -> Dict[str, Any]:+def jwt_base_payload(+ exp_delta: Optional[timedelta], token_owner: str+) -> Dict[str, Any]:utc_now = datetime.utcnow()- payload = {"iat": utc_now, "exp": utc_now + exp_delta}+ payload = {"iat": utc_now, JWT_OWNER_FIELD: token_owner}+ if exp_delta:+ payload["exp"] = utc_now + exp_deltareturn payloaddef jwt_user_payload(user: User,token_type: str,- exp_delta: timedelta,+ exp_delta: Optional[timedelta],additional_payload: Optional[Dict[str, Any]] = None,+ token_owner: str = JWT_SALEOR_OWNER_NAME,) -> Dict[str, Any]:- payload = jwt_base_payload(exp_delta)+ payload = jwt_base_payload(exp_delta, token_owner)payload.update({"token": user.jwt_token_key,@@ -57,17 +68,17 @@ def jwt_encode(payload: Dict[str, Any]) -> str:)-def jwt_decode(token: str) -> Dict[str, Any]:+def jwt_decode(token: str, verify_expiration=settings.JWT_EXPIRE) -> Dict[str, Any]:return jwt.decode(token,settings.SECRET_KEY, # type: ignorealgorithms=[JWT_ALGORITHM],- options={"verify_exp": settings.JWT_EXPIRE},+ options={"verify_exp": verify_expiration},)def create_token(payload: Dict[str, Any], exp_delta: timedelta) -> str:- payload.update(jwt_base_payload(exp_delta))+ payload.update(jwt_base_payload(exp_delta, token_owner=JWT_SALEOR_OWNER_NAME))return jwt_encode(payload)@@ -115,8 +126,30 @@ def get_user_from_payload(payload: Dict[str, Any]) -> Optional[User]:return user+def is_token_belong_to_saleor(token: str) -> bool:+ """Confirm that token was generated by Saleor not by plugin."""+ try:+ payload = jwt.decode(token, options={"verify_signature": False})+ except jwt.PyJWTError:+ return False+ owner = payload.get(JWT_OWNER_FIELD)+ if not owner:+ raise jwt.InvalidTokenError(+ "Invalid token. Create new one by using tokenCreate mutation."+ )+ if owner != JWT_SALEOR_OWNER_NAME:+ return False+ return True++def get_user_from_access_token(token: str) -> Optional[User]:+ if not is_token_belong_to_saleor(token):+ return Nonepayload = jwt_decode(token)+ return get_user_from_access_payload(payload)+++def get_user_from_access_payload(payload: dict) -> Optional[User]:jwt_type = payload.get("type")if jwt_type not in [JWT_ACCESS_TYPE, JWT_THIRDPARTY_ACCESS_TYPE]:raise jwt.InvalidTokenError(@@ -127,9 +160,8 @@ def get_user_from_access_token(token: str) -> Optional[User]:if user and permissions is not None:token_permissions = get_permissions_from_names(permissions)token_codenames = [perm.codename for perm in token_permissions]- user.effective_permissions = user.effective_permissions.filter(- codename__in=token_codenames- )+ user.effective_permissions = get_permissions_from_codenames(token_codenames)+ user.is_staff = True if user.effective_permissions else Falsereturn userdiff --git a/saleor/core/permissions.py b/saleor/core/permissions.pyindex 6bb8d2bb7a..5ce97ec09a 100644--- a/saleor/core/permissions.py+++ b/saleor/core/permissions.py@@ -143,8 +143,12 @@ def get_permissions(permissions=None):codenames = get_permissions_codename()else:codenames = split_permission_codename(permissions)+ return get_permissions_from_codenames(codenames)+++def get_permissions_from_codenames(permission_codenames: List[str]):return (- Permission.objects.filter(codename__in=codenames)+ Permission.objects.filter(codename__in=permission_codenames).prefetch_related("content_type").order_by("codename"))diff --git a/saleor/core/tests/test_auth_backend.py b/saleor/core/tests/test_auth_backend.pyindex e19cee43ba..6d1dd1ab5d 100644--- a/saleor/core/tests/test_auth_backend.py+++ b/saleor/core/tests/test_auth_backend.py@@ -43,6 +43,34 @@ def test_incorect_type_of_token(rf, staff_user):backend.authenticate(request)+def test_saleor_is_not_owner_of_token(rf, staff_user, settings):+ payload = jwt_user_payload(+ staff_user,+ JWT_ACCESS_TYPE,+ settings.JWT_TTL_ACCESS,+ token_owner="mirumee.custom.auth.plugin",+ )+ token = jwt_encode(payload)+ request = rf.request(HTTP_AUTHORIZATION=f"JWT {token}")+ backend = JSONWebTokenBackend()++ assert backend.authenticate(request) is None+++def test_raises_error_when_owner_field_is_missing(rf, staff_user, settings):+ payload = jwt_user_payload(+ staff_user,+ JWT_ACCESS_TYPE,+ settings.JWT_TTL_ACCESS,+ token_owner=None, # type: ignore+ )+ token = jwt_encode(payload)+ request = rf.request(HTTP_AUTHORIZATION=f"JWT {token}")+ backend = JSONWebTokenBackend()+ with pytest.raises(InvalidTokenError):+ backend.authenticate(request)++def test_incorrect_token(rf, staff_user, settings):payload = jwt_user_payload(staff_user,@@ -136,29 +164,6 @@ def test_user_with_limited_permissions(assert set(user_permissions) == set(limited_permissions)-def test_user_doesnt_have_permissions_from_token(staff_user, app, rf):- staff_user.user_permissions.set(- Permission.objects.filter(- codename__in=["manage_apps", "manage_checkouts", "manage_orders"]- )- )- app.permissions.set(- Permission.objects.filter(codename__in=["manage_apps", "manage_checkouts"])- )- access_token_for_app = create_access_token_for_app(app, staff_user)-- expected_permissions = Permission.objects.filter(codename__in=["manage_checkouts"])-- # user doesn't have the same permissions as in the token- staff_user.user_permissions.set(expected_permissions)-- request = rf.request(HTTP_AUTHORIZATION=f"JWT {access_token_for_app}")- backend = JSONWebTokenBackend()- user = backend.authenticate(request)- assert user == staff_user- assert set(user.effective_permissions) == set(expected_permissions)--def test_user_payload_doesnt_have_user_token(rf, staff_user, settings):access_payload = jwt_user_payload(staff_user, JWT_ACCESS_TYPE, settings.JWT_TTL_ACCESS@@ -170,16 +175,3 @@ def test_user_payload_doesnt_have_user_token(rf, staff_user, settings):backend = JSONWebTokenBackend()with pytest.raises(InvalidTokenError):backend.authenticate(request)---def test_user_has_old_token_type(rf, staff_user, settings):- settings.JWT_EXPIRE = False- access_token = (- "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFkbWluQGV4YW1wbGUuY29tIiwiZ"- "XhwIjoxNTYwMTczNDI2LCJvcmlnSWF0IjoxNTYwMTczMTI2fQ.QrYkGfEqnwC-d--EHATAfXoWURJf"- "lFfbntR7BESI9mg"- )- request = rf.request(HTTP_AUTHORIZATION=f"JWT {access_token}")- backend = JSONWebTokenBackend()- with pytest.raises(InvalidTokenError):- backend.authenticate(request)diff --git a/saleor/graphql/account/mutations/jwt.py b/saleor/graphql/account/mutations/authentication.pysimilarity index 57%rename from saleor/graphql/account/mutations/jwt.pyrename to saleor/graphql/account/mutations/authentication.pyindex e6c49d01e5..6fd575c32b 100644--- a/saleor/graphql/account/mutations/jwt.py+++ b/saleor/graphql/account/mutations/authentication.py@@ -279,3 +279,199 @@ class DeactivateAllUserTokens(BaseMutation):user.jwt_token_key = get_random_string()user.save(update_fields=["jwt_token_key"])return cls()+++class ExternalAuthenticationUrl(BaseMutation):+ """Prepare external authentication url for user by a custom plugin."""++ authentication_data = graphene.JSONString(+ description="The data returned by authentication plugin."+ )++ class Arguments:+ plugin_id = graphene.String(+ description="The ID of the authentication plugin.", required=True+ )+ input = graphene.JSONString(+ required=True,+ description=(+ "The data required by plugin to create external authentication url."+ ),+ )++ class Meta:+ description = "Prepare external authentication url for user by custom plugin."+ error_type_class = AccountError+ error_type_field = "account_errors"++ @classmethod+ def perform_mutation(cls, root, info, **data):+ request = info.context+ plugin_id = data["plugin_id"]+ input_data = data["input"]+ manager = info.context.plugins+ return cls(+ authentication_data=manager.external_authentication_url(+ plugin_id, input_data, request+ )+ )+++class ExternalObtainAccessTokens(BaseMutation):+ """Obtain external access tokens by a custom plugin."""++ token = graphene.String(description="The token, required to authenticate.")+ refresh_token = graphene.String(+ description="The refresh token, required to re-generate external access token."+ )+ csrf_token = graphene.String(+ description="CSRF token required to re-generate external access token."+ )+ user = graphene.Field(User, description="A user instance.")++ class Arguments:+ plugin_id = graphene.String(+ description="The ID of the authentication plugin.", required=True+ )+ input = graphene.JSONString(+ required=True,+ description="The data required by plugin to create authentication data.",+ )++ class Meta:+ description = "Obtain external access tokens for user by custom plugin."+ error_type_class = AccountError+ error_type_field = "account_errors"++ @classmethod+ def perform_mutation(cls, root, info, **data):+ request = info.context+ plugin_id = data["plugin_id"]+ input_data = data["input"]+ manager = info.context.plugins+ access_tokens_response = manager.external_obtain_access_tokens(+ plugin_id, input_data, request+ )+ info.context.refresh_token = access_tokens_response.refresh_token++ if access_tokens_response.user and access_tokens_response.user.id:+ info.context._cached_user = access_tokens_response.user+ access_tokens_response.user.last_login = timezone.now()+ access_tokens_response.user.save(update_fields=["last_login"])++ return cls(+ token=access_tokens_response.token,+ refresh_token=access_tokens_response.refresh_token,+ csrf_token=access_tokens_response.csrf_token,+ user=access_tokens_response.user,+ )+++class ExternalRefresh(BaseMutation):+ """Refresh user's access by a custom plugin."""++ token = graphene.String(description="The token, required to authenticate.")+ refresh_token = graphene.String(+ description="The refresh token, required to re-generate external access token."+ )+ csrf_token = graphene.String(+ description="CSRF token required to re-generate external access token."+ )+ user = graphene.Field(User, description="A user instance.")++ class Arguments:+ plugin_id = graphene.String(+ description="The ID of the authentication plugin.", required=True+ )+ input = graphene.JSONString(+ required=True,+ description="The data required by plugin to proceed the refresh process.",+ )++ class Meta:+ description = "Refresh user's access by custom plugin."+ error_type_class = AccountError+ error_type_field = "account_errors"++ @classmethod+ def perform_mutation(cls, root, info, **data):+ request = info.context+ plugin_id = data["plugin_id"]+ input_data = data["input"]+ manager = info.context.plugins+ access_tokens_response = manager.external_refresh(+ plugin_id, input_data, request+ )+ info.context.refresh_token = access_tokens_response.refresh_token+ if access_tokens_response.user and access_tokens_response.user.id:+ info.context._cached_user = access_tokens_response.user++ return cls(+ token=access_tokens_response.token,+ refresh_token=access_tokens_response.refresh_token,+ csrf_token=access_tokens_response.csrf_token,+ user=access_tokens_response.user,+ )+++class ExternalLogout(BaseMutation):+ """Logout user by a custom plugin."""++ logout_data = graphene.JSONString(+ description="The data returned by authentication plugin."+ )++ class Arguments:+ plugin_id = graphene.String(+ description="The ID of the authentication plugin.", required=True+ )+ input = graphene.JSONString(+ required=True,+ description="The data required by plugin to proceed the logout process.",+ )++ class Meta:+ description = "Logout user by custom plugin."+ error_type_class = AccountError+ error_type_field = "account_errors"++ @classmethod+ def perform_mutation(cls, root, info, **data):+ request = info.context+ plugin_id = data["plugin_id"]+ input_data = data["input"]+ manager = info.context.plugins+ return cls(logout_data=manager.external_logout(plugin_id, input_data, request))+++class ExternalVerify(BaseMutation):+ user = graphene.Field(User, description="User assigned to data.")+ is_valid = graphene.Boolean(+ required=True,+ default_value=False,+ description="Determine if authentication data is valid or not.",+ )+ verify_data = graphene.JSONString(description="External data.")++ class Arguments:+ plugin_id = graphene.String(+ description="The ID of the authentication plugin.", required=True+ )+ input = graphene.JSONString(+ required=True,+ description="The data required by plugin to proceed the verification.",+ )++ class Meta:+ description = "Verify external authentication data by plugin."+ error_type_class = AccountError+ error_type_field = "account_errors"++ @classmethod+ def perform_mutation(cls, root, info, **data):+ request = info.context+ plugin_id = data["plugin_id"]+ input_data = data["input"]+ manager = info.context.plugins+ user, data = manager.external_verify(plugin_id, input_data, request)+ return cls(user=user, is_valid=bool(user), verify_data=data)diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 35f5fa259e..6f73bcc7ee 100644--- a/saleor/graphql/account/mutations/base.py+++ b/saleor/graphql/account/mutations/base.py@@ -24,7 +24,7 @@ from ...core.mutations import (validation_error_to_error_type,)from ...core.types.common import AccountError-from .jwt import CreateToken+from .authentication import CreateTokenBILLING_ADDRESS_FIELD = "default_billing_address"SHIPPING_ADDRESS_FIELD = "default_shipping_address"diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.pyindex 536e6e5798..b43f2769af 100644--- a/saleor/graphql/account/schema.py+++ b/saleor/graphql/account/schema.py@@ -20,18 +20,23 @@ from .mutations.account import (ConfirmEmailChange,RequestEmailChange,)+from .mutations.authentication import (+ CreateToken,+ DeactivateAllUserTokens,+ ExternalAuthenticationUrl,+ ExternalLogout,+ ExternalObtainAccessTokens,+ ExternalRefresh,+ ExternalVerify,+ RefreshToken,+ VerifyToken,+)from .mutations.base import (ConfirmAccount,PasswordChange,RequestPasswordReset,SetPassword,)-from .mutations.jwt import (- CreateToken,- DeactivateAllUserTokens,- RefreshToken,- VerifyToken,-)from .mutations.permission_group import (PermissionGroupCreate,PermissionGroupDelete,@@ -188,6 +193,13 @@ class AccountMutations(graphene.ObjectType):token_verify = VerifyToken.Field()tokens_deactivate_all = DeactivateAllUserTokens.Field()+ external_authentication_url = ExternalAuthenticationUrl.Field()+ external_obtain_access_tokens = ExternalObtainAccessTokens.Field()++ external_refresh = ExternalRefresh.Field()+ external_logout = ExternalLogout.Field()+ external_verify = ExternalVerify.Field()+request_password_reset = RequestPasswordReset.Field()confirm_account = ConfirmAccount.Field()set_password = SetPassword.Field()diff --git a/saleor/graphql/account/tests/mutations/test_external_authentication.py b/saleor/graphql/account/tests/mutations/test_external_authentication.pynew file mode 100644index 0000000000..8a1b4fa5e7--- /dev/null+++ b/saleor/graphql/account/tests/mutations/test_external_authentication.py@@ -0,0 +1,46 @@+import json+from unittest.mock import Mock++from ....tests.utils import get_graphql_content++MUTATION_EXTERNAL_AUTHENTICATION = """+ mutation externalAuthenticationUrl($pluginId: String!, $input: JSONString!){+ externalAuthenticationUrl(pluginId: $pluginId, input: $input){+ authenticationData+ accountErrors{+ field+ message+ }+ }+}+"""+++def test_external_authentication_url_plugin_not_active(api_client, customer_user):+ variables = {+ "pluginId": "pluginID1",+ "input": json.dumps({"redirectUrl": "http://locahost:3000/"}),+ }+ response = api_client.post_graphql(MUTATION_EXTERNAL_AUTHENTICATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalAuthenticationUrl"]+ assert json.loads(data["authenticationData"]) == {}+++def test_external_authentication_url(api_client, customer_user, monkeypatch, rf):+ mocked_plugin_fun = Mock()+ expected_return = {"authorizationUrl": "https://ouath-provider/url"}+ mocked_plugin_fun.return_value = expected_return+ monkeypatch.setattr(+ "saleor.plugins.manager.PluginsManager.external_authentication_url",+ mocked_plugin_fun,+ )+ variables = {+ "pluginId": "pluginID1",+ "input": json.dumps({"redirectUrl": "http://locahost:3000/"}),+ }+ response = api_client.post_graphql(MUTATION_EXTERNAL_AUTHENTICATION, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalAuthenticationUrl"]+ assert json.loads(data["authenticationData"]) == expected_return+ assert mocked_plugin_fun.calleddiff --git a/saleor/graphql/account/tests/mutations/test_external_logout.py b/saleor/graphql/account/tests/mutations/test_external_logout.pynew file mode 100644index 0000000000..465a7845b8--- /dev/null+++ b/saleor/graphql/account/tests/mutations/test_external_logout.py@@ -0,0 +1,42 @@+import json+from unittest.mock import Mock++from ....tests.utils import get_graphql_content++MUTATION_EXTERNAL_LOGOUT = """+ mutation externalLogout($pluginId: String!, $input: JSONString!){+ externalLogout(pluginId: $pluginId, input: $input){+ logoutData+ accountErrors{+ field+ message+ }+ }+}+"""+++def test_external_logout_plugin_not_active(api_client, customer_user):+ variables = {+ "pluginId": "pluginID1",+ "input": json.dumps({"logoutRedirect": "ABCD"}),+ }+ response = api_client.post_graphql(MUTATION_EXTERNAL_LOGOUT, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalLogout"]+ assert json.loads(data["logoutData"]) == {}+++def test_external_logout(api_client, customer_user, monkeypatch, rf):+ mocked_plugin_fun = Mock()+ expected_return = {"logoutRedirectParam": "AVC"}+ mocked_plugin_fun.return_value = expected_return+ monkeypatch.setattr(+ "saleor.plugins.manager.PluginsManager.external_logout", mocked_plugin_fun+ )+ variables = {"pluginId": "pluginID1", "input": json.dumps({"logoutParam": "ABCD"})}+ response = api_client.post_graphql(MUTATION_EXTERNAL_LOGOUT, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalLogout"]+ assert json.loads(data["logoutData"]) == expected_return+ assert mocked_plugin_fun.calleddiff --git a/saleor/graphql/account/tests/mutations/test_external_obtain_access_tokens.py b/saleor/graphql/account/tests/mutations/test_external_obtain_access_tokens.pynew file mode 100644index 0000000000..ec8036744e--- /dev/null+++ b/saleor/graphql/account/tests/mutations/test_external_obtain_access_tokens.py@@ -0,0 +1,70 @@+import json+from unittest.mock import Mock, patch++from .....plugins.base_plugin import ExternalAccessTokens+from ....tests.utils import get_graphql_content++MUTATION_EXTERNAL_REFRESH = """+ mutation externalObtainAccessTokens($pluginId: String!, $input: JSONString!){+ externalObtainAccessTokens(pluginId: $pluginId, input: $input){+ token+ refreshToken+ csrfToken+ user{+ }+ accountErrors{+ field+ message+ }+ }+}+"""+++def test_external_obtain_access_tokens_plugin_not_active(api_client, customer_user):+ variables = {+ "pluginId": "pluginId1",+ "input": json.dumps({"code": "ABCD", "state": "stata-data"}),+ }+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalObtainAccessTokens"]+ assert data["token"] is None+ assert data["refreshToken"] is None+ assert data["csrfToken"] is None+ assert data["user"] is None+++@patch("saleor.core.middleware.jwt_decode")+def test_external_obtain_access_tokens(+ mock_refresh_token_middleware, api_client, customer_user, monkeypatch, rf+):+ expected_token = "token1"+ expected_refresh_token = "refresh2"+ expected_csrf_token = "csrf3"+ mocked_plugin_fun = Mock()+ expected_return = ExternalAccessTokens(+ token=expected_token,+ refresh_token=expected_refresh_token,+ csrf_token=expected_csrf_token,+ user=customer_user,+ )+ mocked_plugin_fun.return_value = expected_return+ monkeypatch.setattr(+ "saleor.plugins.manager.PluginsManager.external_obtain_access_tokens",+ mocked_plugin_fun,+ )+ variables = {+ "pluginId": "pluginId1",+ "input": json.dumps({"code": "ABCD", "state": "stata-data"}),+ }+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalObtainAccessTokens"]+ assert data["token"] == expected_token+ assert data["refreshToken"] == expected_refresh_token+ assert data["csrfToken"] == expected_csrf_token+ assert data["user"]["email"] == customer_user.email+ assert mocked_plugin_fun.called+ assert mock_refresh_token_middleware.calleddiff --git a/saleor/graphql/account/tests/mutations/test_external_refresh.py b/saleor/graphql/account/tests/mutations/test_external_refresh.pynew file mode 100644index 0000000000..2aea705827--- /dev/null+++ b/saleor/graphql/account/tests/mutations/test_external_refresh.py@@ -0,0 +1,63 @@+import json+from unittest.mock import Mock, patch++from .....plugins.base_plugin import ExternalAccessTokens+from ....tests.utils import get_graphql_content++MUTATION_EXTERNAL_REFRESH = """+ mutation externalRefresh($pluginId: String!, $input: JSONString!){+ externalRefresh(pluginId: $pluginId, input: $input){+ token+ refreshToken+ csrfToken+ user{+ }+ accountErrors{+ field+ message+ }+ }+}+"""+++def test_external_refresh_plugin_not_active(api_client, customer_user):+ variables = {"pluginId": "pluginId1", "input": json.dumps({"refreshToken": "ABCD"})}+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalRefresh"]+ assert data["token"] is None+ assert data["refreshToken"] is None+ assert data["csrfToken"] is None+ assert data["user"] is None+++@patch("saleor.core.middleware.jwt_decode")+def test_external_refresh(+ mock_refresh_token_middleware, api_client, customer_user, monkeypatch, rf+):+ expected_token = "token1"+ expected_refresh_token = "refresh2"+ expected_csrf_token = "csrf3"+ mocked_plugin_fun = Mock()+ expected_return = ExternalAccessTokens(+ token=expected_token,+ refresh_token=expected_refresh_token,+ csrf_token=expected_csrf_token,+ user=customer_user,+ )+ mocked_plugin_fun.return_value = expected_return+ monkeypatch.setattr(+ "saleor.plugins.manager.PluginsManager.external_refresh", mocked_plugin_fun+ )+ variables = {"pluginId": "pluginId1", "input": json.dumps({"refreshToken": "ABCD"})}+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalRefresh"]+ assert data["token"] == expected_token+ assert data["refreshToken"] == expected_refresh_token+ assert data["csrfToken"] == expected_csrf_token+ assert data["user"]["email"] == customer_user.email+ assert mocked_plugin_fun.called+ assert mock_refresh_token_middleware.calleddiff --git a/saleor/graphql/account/tests/mutations/test_external_verify.py b/saleor/graphql/account/tests/mutations/test_external_verify.pynew file mode 100644index 0000000000..ae3b520917--- /dev/null+++ b/saleor/graphql/account/tests/mutations/test_external_verify.py@@ -0,0 +1,45 @@+import json+from unittest.mock import Mock++from ....tests.utils import get_graphql_content++MUTATION_EXTERNAL_VERIFY = """+ mutation externalVerify($pluginId: String!, $input: JSONString!){+ externalVerify(pluginId:$pluginId, input: $input){+ verifyData+ user{+ }+ isValid+ accountErrors{+ field+ message+ }+ }+}+"""+++def test_external_verify_plugin_not_active(api_client, customer_user):+ variables = {"pluginId": "pluginId3", "input": json.dumps({"token": "ABCD"})}+ response = api_client.post_graphql(MUTATION_EXTERNAL_VERIFY, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalVerify"]+ assert json.loads(data["verifyData"]) == {}+++def test_external_verify(api_client, customer_user, monkeypatch, rf):+ mocked_plugin_fun = Mock()+ expected_return = customer_user, {"data": "XYZ123"}+ mocked_plugin_fun.return_value = expected_return+ monkeypatch.setattr(+ "saleor.plugins.manager.PluginsManager.external_verify", mocked_plugin_fun+ )+ variables = {"pluginId": "pluginId3", "input": json.dumps({"token": "ABCD"})}+ response = api_client.post_graphql(MUTATION_EXTERNAL_VERIFY, variables)+ content = get_graphql_content(response)+ data = content["data"]["externalVerify"]+ user_email = content["data"]["externalVerify"]["user"]["email"]+ assert json.loads(data["verifyData"]) == {"data": "XYZ123"}+ assert user_email == customer_user.email+ assert mocked_plugin_fun.calleddiff --git a/saleor/graphql/account/tests/mutations/test_token_create_.py b/saleor/graphql/account/tests/mutations/test_token_create.pysimilarity index 97%rename from saleor/graphql/account/tests/mutations/test_token_create_.pyrename to saleor/graphql/account/tests/mutations/test_token_create.pyindex 2c4eb31a6d..1fb633d97d 100644--- a/saleor/graphql/account/tests/mutations/test_token_create_.py+++ b/saleor/graphql/account/tests/mutations/test_token_create.py@@ -72,7 +72,8 @@ def test_create_token(api_client, customer_user, settings):def test_create_token_sets_cookie(api_client, customer_user, settings, monkeypatch):csrf_token = _get_new_csrf_token()monkeypatch.setattr(- "saleor.graphql.account.mutations.jwt._get_new_csrf_token", lambda: csrf_token+ "saleor.graphql.account.mutations.authentication._get_new_csrf_token",+ lambda: csrf_token,)variables = {"email": customer_user.email, "password": customer_user._password}response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 6109624f92..8c10097f43 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1943,6 +1943,49 @@ enum ExportScope {FILTER}+type ExternalAuthentication {+ id: String!+ name: String+}++type ExternalAuthenticationUrl {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ authenticationData: JSONString+ accountErrors: [AccountError!]!+}++type ExternalLogout {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ logoutData: JSONString+ accountErrors: [AccountError!]!+}++type ExternalObtainAccessTokens {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ token: String+ refreshToken: String+ csrfToken: String+ user: User+ accountErrors: [AccountError!]!+}++type ExternalRefresh {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ token: String+ refreshToken: String+ csrfToken: String+ user: User+ accountErrors: [AccountError!]!+}++type ExternalVerify {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ user: User+ isValid: Boolean!+ verifyData: JSONString+ accountErrors: [AccountError!]!+}+type File {url: String!contentType: String@@ -2765,6 +2808,11 @@ type Mutation {tokenRefresh(csrfToken: String, refreshToken: String): RefreshTokentokenVerify(token: String!): VerifyTokentokensDeactivateAll: DeactivateAllUserTokens+ externalAuthenticationUrl(input: JSONString!, pluginId: String!): ExternalAuthenticationUrl+ externalObtainAccessTokens(input: JSONString!, pluginId: String!): ExternalObtainAccessTokens+ externalRefresh(input: JSONString!, pluginId: String!): ExternalRefresh+ externalLogout(input: JSONString!, pluginId: String!): ExternalLogout+ externalVerify(input: JSONString!, pluginId: String!): ExternalVerifyrequestPasswordReset(email: String!, redirectUrl: String!): RequestPasswordResetconfirmAccount(email: String!, token: String!): ConfirmAccountsetPassword(email: String!, password: String!, token: String!): SetPassword@@ -4906,6 +4954,7 @@ input ShippingZoneUpdateInput {type Shop {availablePaymentGateways(currency: String): [PaymentGateway!]!+ availableExternalAuthentications: [ExternalAuthentication!]!availableShippingMethods(channel: String!, address: AddressInput): [ShippingMethod]geolocalization: Geolocalizationcountries(languageCode: LanguageCodeEnum): [CountryDisplay!]!diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex b0770b282b..f1f916ce9a 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -589,6 +589,40 @@ def test_query_geolocalization(user_api_client):assert data["country"] is None+AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY = """+ query{+ shop {+ availableExternalAuthentications{+ id+ name+ }+ }+ }+"""+++ "external_auths",+ [+ [{"id": "auth1", "name": "Auth-1"}],+ [{"id": "auth1", "name": "Auth-1"}, {"id": "auth2", "name": "Auth-2"}],+ [],+ ],+)+def test_query_available_external_authentications(+ external_auths, user_api_client, monkeypatch+):+ monkeypatch.setattr(+ "saleor.plugins.manager.PluginsManager.list_external_authentications",+ lambda self, active_only: external_auths,+ )+ query = AVAILABLE_EXTERNAL_AUTHENTICATIONS_QUERY+ response = user_api_client.post_graphql(query)+ content = get_graphql_content(response)+ data = content["data"]["shop"]["availableExternalAuthentications"]+ assert data == external_auths++AVAILABLE_PAYMENT_GATEWAYS_QUERY = """query Shop($currency: String){shop {diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex 3dc2dbae3e..b7f060382c 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -66,6 +66,13 @@ class OrderSettings(CountableDjangoObjectType):model = site_models.SiteSettings+class ExternalAuthentication(graphene.ObjectType):+ id = graphene.String(+ description="ID of external authentication plugin.", required=True+ )+ name = graphene.String(description="Name of external authentication plugin.")++class Shop(graphene.ObjectType):available_payment_gateways = graphene.List(graphene.NonNull(PaymentGateway),@@ -77,6 +84,11 @@ class Shop(graphene.ObjectType):description="List of available payment gateways.",required=True,)+ available_external_authentications = graphene.List(+ graphene.NonNull(ExternalAuthentication),+ description="List of available external authentications.",+ required=True,+ )available_shipping_methods = graphene.List(ShippingMethod,channel=graphene.Argument(@@ -181,6 +193,10 @@ class Shop(graphene.ObjectType):def resolve_available_payment_gateways(_, _info, currency: Optional[str] = None):return get_plugins_manager().list_payment_gateways(currency=currency)+ @staticmethod+ def resolve_available_external_authentications(_, info):+ return info.context.plugins.list_external_authentications(active_only=True)+@staticmethoddef resolve_available_shipping_methods(_, info, channel, address=None):return resolve_available_shipping_methods(info, channel, address)diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 32241f9fd8..a1d7e472e7 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -1,6 +1,7 @@from copy import copy+from dataclasses import dataclassfrom decimal import Decimal-from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Union+from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Unionfrom django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse@@ -26,6 +27,7 @@ if TYPE_CHECKING:from ..discount import DiscountInfofrom ..invoice.models import Invoicefrom ..order.models import Fulfillment, Order, OrderLine+ from ..page.models import Pagefrom ..product.models import (Collection,Product,@@ -53,6 +55,14 @@ class ConfigurationTypeField:]+@dataclass+class ExternalAccessTokens:+ token: Optional[str] = None+ refresh_token: Optional[str] = None+ csrf_token: Optional[str] = None+ user: Optional["User"] = None++class BasePlugin:"""Abstract class for storing all methods available for any plugin.@@ -75,6 +85,59 @@ class BasePlugin:def __str__(self):return self.PLUGIN_NAME+ def external_authentication_url(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> dict:+ """Handle authentication request.++ Overwrite this method if the plugin handles authentication flow.+ """+ return NotImplemented++ def external_obtain_access_tokens(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> ExternalAccessTokens:+ """Handle authentication request responsible for obtaining access tokens.++ Overwrite this method if the plugin handles authentication flow.+ """+ return NotImplemented++ def external_refresh(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> ExternalAccessTokens:+ """Handle authentication refresh request.++ Overwrite this method if the plugin handles authentication flow and supports+ refreshing the access.+ """+ return NotImplemented++ def external_logout(self, data: dict, request: WSGIRequest, previous_value):+ """Handle logout request.++ Overwrite this method if the plugin handles logout flow.+ """+ return NotImplemented++ def external_verify(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> Tuple[Optional["User"], dict]:+ """Verify the provided authentication data.++ Overwrite this method if the plugin should validate the authentication data.+ """+ return NotImplemented++ def authenticate_user(+ self, request: WSGIRequest, previous_value+ ) -> Optional["User"]:+ """Authenticate user which should be assigned to the request.++ Overwrite this method if the plugin handles authentication flow.+ """+ return NotImplemented+def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:"""Handle received http request.diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 2ce881f809..60a14d5fec 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -1,5 +1,5 @@from decimal import Decimal-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union+from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Unionimport opentracingfrom django.conf import settings@@ -14,6 +14,7 @@ from ..core.payments import PaymentInterfacefrom ..core.prices import quantize_pricefrom ..core.taxes import TaxType, zero_taxed_moneyfrom ..discount import DiscountInfo+from .base_plugin import ExternalAccessTokensfrom .models import PluginConfigurationif TYPE_CHECKING:@@ -555,6 +556,17 @@ class PluginsManager(PaymentInterface):gateways.append(gateway)return gateways+ def list_external_authentications(self, active_only: bool = True) -> List[dict]:+ plugins = self.plugins+ auth_basic_method = "external_obtain_access_tokens"+ if active_only:+ plugins = self.get_active_plugins()+ return [+ {"id": plugin.PLUGIN_ID, "name": plugin.PLUGIN_NAME}+ for plugin in plugins+ if auth_basic_method in type(plugin).__dict__+ ]+def checkout_available_payment_gateways(self,checkout: "Checkout",@@ -665,6 +677,61 @@ class PluginsManager(PaymentInterface):plugin, "webhook", default_value, request, path)+ def external_obtain_access_tokens(+ self, plugin_id: str, data: dict, request: WSGIRequest+ ) -> Optional["ExternalAccessTokens"]:+ """Obtain access tokens from authentication plugin."""+ default_value = ExternalAccessTokens()+ plugin = self.get_plugin(plugin_id)+ return self.__run_method_on_single_plugin(+ plugin, "external_obtain_access_tokens", default_value, data, request+ )++ def external_authentication_url(+ self, plugin_id: str, data: dict, request: WSGIRequest+ ) -> dict:+ """Handle authentication request."""+ default_value = {} # type: ignore+ plugin = self.get_plugin(plugin_id)+ return self.__run_method_on_single_plugin(+ plugin, "external_authentication_url", default_value, data, request+ )++ def external_refresh(+ self, plugin_id: str, data: dict, request: WSGIRequest+ ) -> Optional["ExternalAccessTokens"]:+ """Handle authentication refresh request."""+ default_value = ExternalAccessTokens()+ plugin = self.get_plugin(plugin_id)+ return self.__run_method_on_single_plugin(+ plugin, "external_refresh", default_value, data, request+ )++ def authenticate_user(self, request: WSGIRequest) -> Optional["User"]:+ """Authenticate user which should be assigned to the request."""+ default_value = None+ return self.__run_method_on_plugins("authenticate_user", default_value, request)++ def external_logout(self, plugin_id: str, data: dict, request: WSGIRequest) -> dict:+ """Logout the user."""+ default_value: Dict[str, str] = {}+ plugin = self.get_plugin(plugin_id)+ return self.__run_method_on_single_plugin(+ plugin, "external_logout", default_value, data, request+ )++ def external_verify(+ self, plugin_id: str, data: dict, request: WSGIRequest+ ) -> Tuple[Optional["User"], dict]:+ """Verify the provided authentication data."""+ default_data: Dict[str, str] = dict()+ default_user: Optional["User"] = None+ default_value = default_user, default_data+ plugin = self.get_plugin(plugin_id)+ return self.__run_method_on_single_plugin(+ plugin, "external_verify", default_value, data, request+ )+def get_plugins_manager(manager_path: str = None, plugins: List[str] = Nonediff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.pyindex c674b2bb44..e99acec827 100644--- a/saleor/plugins/tests/sample_plugins.py+++ b/saleor/plugins/tests/sample_plugins.py@@ -1,19 +1,20 @@from decimal import Decimal-from typing import TYPE_CHECKING, Iterable, Optional, Union+from typing import TYPE_CHECKING, Iterable, Optional, Tuple, Unionfrom django.core.handlers.wsgi import WSGIRequestfrom django.http import HttpResponse, HttpResponseNotFound, JsonResponsefrom django_countries.fields import Countryfrom prices import Money, TaxedMoney+from ...account.models import Userfrom ...core.taxes import TaxType-from ..base_plugin import BasePlugin, ConfigurationTypeField+from ..base_plugin import BasePlugin, ConfigurationTypeField, ExternalAccessTokensif TYPE_CHECKING:# flake8: noqafrom ...account.models import Addressfrom ...checkout import CheckoutLineInfo- from ...checkout.models import Checkout, CheckoutLine+ from ...checkout.models import Checkoutfrom ...discount import DiscountInfofrom ...order.models import Orderfrom ...product.models import Product, ProductType@@ -135,6 +136,39 @@ class PluginSample(BasePlugin):) -> Decimal:return Decimal("15.0").quantize(Decimal("1."))+ def external_authentication_url(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> dict:+ return {"authorizeUrl": "http://www.auth.provider.com/authorize/"}++ def external_obtain_access_tokens(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> ExternalAccessTokens:+ return ExternalAccessTokens(+ token="token1", refresh_token="refresh2", csrf_token="csrf3"+ )++ def external_refresh(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> ExternalAccessTokens:+ return ExternalAccessTokens(+ token="token4", refresh_token="refresh5", csrf_token="csrf6"+ )++ def external_verify(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> Tuple[Optional[User], dict]:+ user = User.objects.get()+ return user, {"some_data": "data"}++ def authenticate_user(+ self, request: WSGIRequest, previous_value+ ) -> Optional["User"]:+ return User.objects.filter().first()++ def external_logout(self, data: dict, request: WSGIRequest, previous_value) -> dict:+ return {"logoutUrl": "http://www.auth.provider.com/logout/"}+def get_checkout_line_tax_rate(self,checkout: "Checkout",@@ -173,6 +207,13 @@ class PluginInactive(BasePlugin):PLUGIN_NAME = "PluginInactive"PLUGIN_DESCRIPTION = "Test plugin description_2"+ def external_obtain_access_tokens(+ self, data: dict, request: WSGIRequest, previous_value+ ) -> ExternalAccessTokens:+ return ExternalAccessTokens(+ token="token1", refresh_token="refresh2", csrf_token="csrf3"+ )+class ActivePlugin(BasePlugin):PLUGIN_ID = "plugin.active"diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.pyindex 7e29bef0c9..acad769cb5 100644--- a/saleor/plugins/tests/test_manager.py+++ b/saleor/plugins/tests/test_manager.py@@ -11,6 +11,7 @@ from ...checkout.utils import fetch_checkout_linesfrom ...core.taxes import TaxTypefrom ...payment.interface import PaymentGatewayfrom ...product.models import Product+from ..base_plugin import ExternalAccessTokensfrom ..manager import PluginsManager, get_plugins_managerfrom ..models import PluginConfigurationfrom ..tests.sample_plugins import (@@ -630,3 +631,116 @@ def test_manager_inncorrect_plugin(rf):response = manager.webhook(request, "incorrect.plugin.id")assert isinstance(response, HttpResponseNotFound)assert response.status_code == 404+++def test_manager_external_authentication(rf):+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ manager = PluginsManager(plugins=plugins)++ response = manager.external_authentication_url(+ PluginSample.PLUGIN_ID, {"redirectUrl": "ABC"}, rf.request()+ )+ assert response == {"authorizeUrl": "http://www.auth.provider.com/authorize/"}+++def test_manager_external_refresh(rf):+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ manager = PluginsManager(plugins=plugins)+ response = manager.external_refresh(+ PluginSample.PLUGIN_ID, {"refreshToken": "ABC11"}, rf.request()+ )++ expected_plugin_response = ExternalAccessTokens(+ token="token4", refresh_token="refresh5", csrf_token="csrf6"+ )+ assert response == expected_plugin_response+++def test_manager_external_obtain_access_tokens(rf):+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ manager = PluginsManager(plugins=plugins)+ response = manager.external_obtain_access_tokens(+ PluginSample.PLUGIN_ID, {"code": "ABC11", "state": "state1"}, rf.request()+ )++ expected_plugin_response = ExternalAccessTokens(+ token="token1", refresh_token="refresh2", csrf_token="csrf3"+ )+ assert response == expected_plugin_response+++def test_manager_authenticate_user(rf, admin_user):+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ manager = PluginsManager(plugins=plugins)+ user = manager.authenticate_user(rf.request())+ assert user == admin_user+++def test_manager_external_logout(rf, admin_user):+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ manager = PluginsManager(plugins=plugins)+ response = manager.external_logout(PluginSample.PLUGIN_ID, {}, rf.request())+ assert response == {"logoutUrl": "http://www.auth.provider.com/logout/"}+++def test_manager_external_verify(rf, admin_user):+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ manager = PluginsManager(plugins=plugins)+ user, response_data = manager.external_verify(+ PluginSample.PLUGIN_ID, {}, rf.request()+ )+ assert user == admin_user+ assert response_data == {"some_data": "data"}+++def test_list_external_authentications():+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.ActivePaymentGateway",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]+ manager = PluginsManager(plugins=plugins)+ external_auths = manager.list_external_authentications(active_only=False)++ assert {+ "id": PluginInactive.PLUGIN_ID,+ "name": PluginInactive.PLUGIN_NAME,+ } in external_auths+ assert {+ "id": PluginSample.PLUGIN_ID,+ "name": PluginSample.PLUGIN_NAME,+ } in external_auths+++def test_list_external_authentications_active_only():+ plugins = [+ "saleor.plugins.tests.sample_plugins.PluginInactive",+ "saleor.plugins.tests.sample_plugins.ActivePaymentGateway",+ "saleor.plugins.tests.sample_plugins.PluginSample",+ ]++ manager = PluginsManager(plugins=plugins)+ external_auths = manager.list_external_authentications(active_only=True)++ assert {+ "id": PluginSample.PLUGIN_ID,+ "name": PluginSample.PLUGIN_NAME,+ } in external_authsdiff --git a/saleor/settings.py b/saleor/settings.pyindex 042ee60dd3..ba16ce5400 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -467,6 +467,7 @@ DEFAULT_PLACEHOLDER = "images/placeholder255x255.png"AUTHENTICATION_BACKENDS = ["saleor.core.auth_backend.JSONWebTokenBackend",+ "saleor.core.auth_backend.PluginBackend",]# CELERY SETTINGS