Commit aeff0ab5 authored by ibuler's avatar ibuler

[Update] 修改public key 校验

parent 0b211d33
# -*- coding: utf-8 -*-
#
from django.contrib.auth import get_user_model
UserModel = get_user_model()
__all__ = ['PublicKeyAuthBackend']
class PublicKeyAuthBackend:
def authenticate(self, request, username=None, public_key=None, **kwargs):
if not public_key:
return None
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 \
self.user_can_authenticate(user):
return user
@staticmethod
def user_can_authenticate(user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, 'is_active', None)
return is_active or is_active is None
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
......@@ -33,17 +33,9 @@ def check_user_valid(**kwargs):
elif user.password_has_expired:
return None, errors.reason_password_expired
if password:
user = authenticate(request, username=username, password=password)
if password or public_key:
user = authenticate(request, username=username,
password=password, public_key=public_key)
if user:
return user, ''
if public_key and user.public_key:
public_key_saved = user.public_key.split()
if len(public_key_saved) == 1:
public_key_saved = public_key_saved[0]
else:
public_key_saved = public_key_saved[1]
if public_key == public_key_saved:
return user, ''
return None, errors.reason_password_failed
......@@ -411,6 +411,7 @@ REST_FRAMEWORK = {
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'authentication.backends.pubkey.PublicKeyAuthBackend',
]
# Custom User Auth model
......
......@@ -120,6 +120,23 @@ class AuthMixin:
return s
return False
@staticmethod
def get_public_key_body(key):
for i in key.split():
if len(i) > 256:
return i
return key
def check_public_key(self, key):
if not self.public_key:
return False
key = self.get_public_key_body(key)
key_saved = self.get_public_key_body(self.public_key)
if key == key_saved:
return True
else:
return False
class RoleMixin:
ROLE_ADMIN = 'Admin'
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment