jumpserver/apps/authentication/backends/pubkey.py

43 lines
1.3 KiB
Python
Raw Normal View History

2019-11-11 04:43:00 +00:00
# -*- coding: utf-8 -*-
#
from django.conf import settings
2023-09-25 14:58:12 +00:00
from django.contrib.auth import get_user_model
2023-09-25 14:58:12 +00:00
from common.permissions import ServiceAccountSignaturePermission
from .base import JMSBaseAuthBackend
2019-11-11 04:43:00 +00:00
UserModel = get_user_model()
__all__ = ['PublicKeyAuthBackend']
class PublicKeyAuthBackend(JMSBaseAuthBackend):
@staticmethod
def is_enabled():
return settings.TERMINAL_PUBLIC_KEY_AUTH
2019-11-11 04:43:00 +00:00
def authenticate(self, request, username=None, public_key=None, **kwargs):
if not public_key:
return None
2023-09-25 14:58:12 +00:00
permission = ServiceAccountSignaturePermission()
if not permission.has_permission(request, None):
return None
2019-11-11 04:43:00 +00:00
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
return None
else:
if user.check_public_key(public_key) and \
2023-09-25 14:58:12 +00:00
self.user_can_authenticate(user):
2019-11-11 04:43:00 +00:00
return user
def get_user(self, user_id):
try:
user = UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
return user if self.user_can_authenticate(user) else None