Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Validate authentication in validate_plugin_configuration
IKarbowiake41640ffad4d
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.pyindex b74f8b315d..1f4ff79003 100644--- a/saleor/plugins/avatax/__init__.py+++ b/saleor/plugins/avatax/__init__.py@@ -98,10 +98,12 @@ def api_post_request(return json_response # type: ignore-def api_get_request(url: str, config: AvataxConfiguration):+def api_get_request(+ url: str, username_or_account: str, password_or_license: str,+):response = Nonetry:- auth = HTTPBasicAuth(config.username_or_account, config.password_or_license)+ auth = HTTPBasicAuth(username_or_account, password_or_license)response = requests.get(url, auth=auth, timeout=TIMEOUT)json_response = response.json()logger.debug("[GET] Hit to %s", url)@@ -453,7 +455,9 @@ def get_cached_tax_codes_or_fetch(tax_codes = cache.get(TAX_CODES_CACHE_KEY, {})if not tax_codes:tax_codes_url = urljoin(get_api_url(config.use_sandbox), "definitions/taxcodes")- response = api_get_request(tax_codes_url, config)+ response = api_get_request(+ tax_codes_url, config.username_or_account, config.password_or_license+ )if response and "error" not in response:tax_codes = generate_tax_codes_dict(response)cache.set(TAX_CODES_CACHE_KEY, tax_codes, cache_time)diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.pyindex 83229471c5..cd827df43d 100644--- a/saleor/plugins/avatax/plugin.py+++ b/saleor/plugins/avatax/plugin.py@@ -20,6 +20,7 @@ from . import (TransactionType,_validate_checkout,_validate_order,+ api_get_request,api_post_request,generate_request_data_from_checkout,get_api_url,@@ -421,6 +422,24 @@ class AvataxPlugin(BasePlugin):get_cached_tax_codes_or_fetch(self.config)return True+ @classmethod+ def validate_authentication(cls, plugin_configuration: "PluginConfiguration"):+ conf = {+ data["name"]: data["value"] for data in plugin_configuration.configuration+ }+ url = urljoin(get_api_url(conf["Use sandbox"]), "utilities/ping")+ response = api_get_request(+ url,+ username_or_account=conf["Username or account"],+ password_or_license=conf["Password or license"],+ )++ if not response.get("authenticated"):+ raise ValidationError(+ "Authentication failed. Please check provided data.",+ code=PluginErrorCode.PLUGIN_MISCONFIGURED.value,+ )+@classmethoddef validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):"""Validate if provided configuration is correct."""@@ -432,12 +451,18 @@ class AvataxPlugin(BasePlugin):if not configuration["Password or license"]:missing_fields.append("Password or license")- if plugin_configuration.active and missing_fields:- error_msg = (- "To enable a plugin, you need to provide values for the "- "following fields: "- )- raise ValidationError(- error_msg + ", ".join(missing_fields),- code=PluginErrorCode.PLUGIN_MISCONFIGURED.value,- )+ if plugin_configuration.active:+ if missing_fields:+ error_msg = (+ "To enable a plugin, you need to provide values for the "+ "following fields: "+ )+ raise ValidationError(+ error_msg + ", ".join(missing_fields),+ code=PluginErrorCode.PLUGIN_MISCONFIGURED.value,+ )++ try:+ cls.validate_authentication(plugin_configuration)+ except ValidationError:+ raisediff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex 5c4a4eb961..05d8c0734a 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -476,8 +476,10 @@ def test_get_plugin_configuration(settings):assert "Autocommit" in configuration_fields-def test_save_plugin_configuration(settings):+@patch("saleor.plugins.avatax.plugin.api_get_request")+def test_save_plugin_configuration(api_get_request_mock, settings):settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]+ api_get_request_mock.return_value = {"authenticated": True}manager = get_plugins_manager()manager.save_plugin_configuration(AvataxPlugin.PLUGIN_ID,@@ -495,6 +497,32 @@ def test_save_plugin_configuration(settings):assert plugin_configuration.active+@patch("saleor.plugins.avatax.plugin.api_get_request")+def test_save_plugin_configuration_authentication_failed(+ api_get_request_mock, settings+):+ # given+ settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]+ api_get_request_mock.return_value = {"authenticated": False}+ manager = get_plugins_manager()++ # when+ with pytest.raises(ValidationError) as e:+ manager.save_plugin_configuration(+ AvataxPlugin.PLUGIN_ID,+ {+ "configuration": [+ {"name": "Username or account", "value": "test"},+ {"name": "Password or license", "value": "test"},+ {"name": "Active", "value": True},+ ],+ },+ )++ # then+ assert e._excinfo[1].args[0] == "Authentication failed. Please check provided data."++def test_save_plugin_configuration_cannot_be_enabled_without_config(settings, plugin_configuration):@@ -653,7 +681,9 @@ def test_api_get_request_handles_request_errors(product, monkeypatch):)url = "https://www.avatax.api.com/some-get-path"- response = api_get_request(url, config)+ response = api_get_request(+ url, config.username_or_account, config.password_or_license+ )assert response == {}assert mocked_response.called@@ -668,7 +698,9 @@ def test_api_get_request_handles_json_errors(product, monkeypatch):)url = "https://www.avatax.api.com/some-get-path"- response = api_get_request(url, config)+ response = api_get_request(+ url, config.username_or_account, config.password_or_license+ )assert response == {}assert mocked_response.called