diff --git a/frappe/auth.py b/frappe/auth.py index 4b53e76533..f3fbe272c5 100644 --- a/frappe/auth.py +++ b/frappe/auth.py @@ -574,13 +574,13 @@ def validate_auth(): validate_oauth(authorization_header) validate_auth_via_api_keys(authorization_header) - # If login via bearer, basic or keypair didn't work then authentication failed and we - # should terminate here. - if frappe.session.user in ("", "Guest"): - raise frappe.AuthenticationError - validate_auth_via_hooks() + # If login via bearer, basic or keypair didn't work then authentication failed and we + # should terminate here. + if len(authorization_header) == 2 and frappe.session.user in ("", "Guest"): + raise frappe.AuthenticationError + def validate_oauth(authorization_header): """ @@ -621,7 +621,7 @@ def validate_oauth(authorization_header): frappe.set_user(frappe.db.get_value("OAuth Bearer Token", token, "user")) frappe.local.form_dict = form_dict except AttributeError: - raise frappe.AuthenticationError + pass def validate_auth_via_api_keys(authorization_header): diff --git a/frappe/tests/test_hooks.py b/frappe/tests/test_hooks.py index 41a734e7ad..970699d01c 100644 --- a/frappe/tests/test_hooks.py +++ b/frappe/tests/test_hooks.py @@ -1,10 +1,10 @@ # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE - import frappe from frappe.cache_manager import clear_controller_cache from frappe.desk.doctype.todo.todo import ToDo -from frappe.tests.utils import FrappeTestCase +from frappe.tests.test_api import FrappeAPITestCase +from frappe.tests.utils import FrappeTestCase, patch_hooks class TestHooks(FrappeTestCase): @@ -96,10 +96,28 @@ class TestHooks(FrappeTestCase): event.delete() +class TestAPIHooks(FrappeAPITestCase): + def test_auth_hook(self): + with patch_hooks({"auth_hooks": ["frappe.tests.test_hooks.custom_auth"]}): + site_url = frappe.utils.get_site_url(frappe.local.site) + response = self.get( + site_url + "/api/method/frappe.auth.get_logged_user", + headers={"Authorization": "Bearer set_test_example_user"}, + ) + # Test! + self.assertTrue(response.json.get("message") == "test@example.com") + + def custom_has_permission(doc, ptype, user): if doc.flags.dont_touch_me: return False +def custom_auth(): + auth_type, token = frappe.get_request_header("Authorization", "Bearer ").split(" ") + if token == "set_test_example_user": + frappe.set_user("test@example.com") + + class CustomToDo(ToDo): pass