2022-02-25 11:23:59 +00:00
|
|
|
from django.contrib.auth.backends import ModelBackend
|
2022-04-13 12:24:56 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2022-02-25 11:23:59 +00:00
|
|
|
|
|
|
|
from users.models import User
|
|
|
|
from common.utils import get_logger
|
|
|
|
|
|
|
|
|
2022-04-13 12:24:56 +00:00
|
|
|
UserModel = get_user_model()
|
2022-02-25 11:23:59 +00:00
|
|
|
logger = get_logger(__file__)
|
|
|
|
|
|
|
|
|
|
|
|
class JMSBaseAuthBackend:
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def is_enabled():
|
|
|
|
return True
|
|
|
|
|
|
|
|
def has_perm(self, user_obj, perm, obj=None):
|
|
|
|
return False
|
|
|
|
|
|
|
|
def user_can_authenticate(self, user):
|
2022-02-28 11:28:58 +00:00
|
|
|
"""
|
|
|
|
Reject users with is_valid=False. Custom user models that don't have
|
|
|
|
that attribute are allowed.
|
|
|
|
"""
|
2022-03-16 12:41:54 +00:00
|
|
|
# 在 check_user_auth 中进行了校验,可以返回对应的错误信息
|
|
|
|
# is_valid = getattr(user, 'is_valid', None)
|
|
|
|
# return is_valid or is_valid is None
|
|
|
|
return True
|
2022-02-25 11:23:59 +00:00
|
|
|
|
2022-02-28 11:28:58 +00:00
|
|
|
# allow user to authenticate
|
|
|
|
def username_allow_authenticate(self, username):
|
|
|
|
return self.allow_authenticate(username=username)
|
|
|
|
|
|
|
|
def user_allow_authenticate(self, user):
|
|
|
|
return self.allow_authenticate(user=user)
|
2022-02-25 11:23:59 +00:00
|
|
|
|
|
|
|
def allow_authenticate(self, user=None, username=None):
|
|
|
|
if user:
|
2022-02-28 11:28:58 +00:00
|
|
|
allowed_backend_paths = user.get_allowed_auth_backend_paths()
|
2022-02-25 11:23:59 +00:00
|
|
|
else:
|
2022-02-28 11:28:58 +00:00
|
|
|
allowed_backend_paths = User.get_user_allowed_auth_backend_paths(username)
|
|
|
|
if allowed_backend_paths is None:
|
2022-02-25 11:23:59 +00:00
|
|
|
# 特殊值 None 表示没有限制
|
|
|
|
return True
|
2022-02-28 11:28:58 +00:00
|
|
|
backend_name = self.__class__.__name__
|
|
|
|
allowed_backend_names = [path.split('.')[-1] for path in allowed_backend_paths]
|
|
|
|
allow = backend_name in allowed_backend_names
|
2022-02-25 11:23:59 +00:00
|
|
|
if not allow:
|
|
|
|
info = 'User {} skip authentication backend {}, because it not in {}'
|
2022-02-28 11:28:58 +00:00
|
|
|
info = info.format(username, backend_name, ','.join(allowed_backend_names))
|
2022-02-25 11:23:59 +00:00
|
|
|
logger.debug(info)
|
|
|
|
return allow
|
|
|
|
|
|
|
|
|
|
|
|
class JMSModelBackend(JMSBaseAuthBackend, ModelBackend):
|
|
|
|
pass
|