Merge pull request #23255 from revant/fix-auth-hooks

fix: call auth hooks before raising error
This commit is contained in:
mergify[bot] 2023-11-18 06:09:29 +00:00 committed by GitHub
commit e9e7f33792
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 8 deletions

View file

@ -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):

View file

@ -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