From 9ed7c41514212a77bf904e916ca8a5105a6f14ae Mon Sep 17 00:00:00 2001 From: Bai Date: Tue, 10 Dec 2024 16:33:25 +0800 Subject: [PATCH] fix: fixed an issue when third-part user auth --- apps/authentication/backends/base.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/apps/authentication/backends/base.py b/apps/authentication/backends/base.py index 13e99f2c6..5ae84c684 100644 --- a/apps/authentication/backends/base.py +++ b/apps/authentication/backends/base.py @@ -23,10 +23,9 @@ class JMSBaseAuthBackend: Reject users with is_valid=False. Custom user models that don't have that attribute are allowed. """ - # 在 check_user_auth 中进行了校验,可以返回对应的错误信息 - # is_valid = getattr(user, 'is_valid', None) - # return is_valid or is_valid is None - return True + # 三方用户认证完成后,在后续的 get_user 获取逻辑中,也应该需要检查用户是否有效 + is_valid = getattr(user, 'is_valid', None) + return is_valid or is_valid is None # allow user to authenticate def username_allow_authenticate(self, username): @@ -44,7 +43,7 @@ class JMSBaseAuthBackend: # 特殊值 None 表示没有限制 return True backend_name = self.__class__.__name__ - allowed_backend_names = [path.split('.')[-1] for path in allowed_backend_paths] + allowed_backend_names = [path.split('.drf.py')[-1] for path in allowed_backend_paths] allow = backend_name in allowed_backend_names if not allow: info = 'User {} skip authentication backend {}, because it not in {}' @@ -52,6 +51,14 @@ class JMSBaseAuthBackend: logger.info(info) return allow + def get_user(self, user_id): + """ 三方用户认证成功后 request.user 赋值时会调用 backend 的当前方法获取用户 """ + try: + user = UserModel._default_manager.get(pk=user_id) + except UserModel.DoesNotExist: + return None + return user if self.user_can_authenticate(user) else None + class JMSModelBackend(JMSBaseAuthBackend, ModelBackend): pass