2019-01-07 11:20:39 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2020-07-31 11:40:27 +00:00
|
|
|
import traceback
|
2019-01-07 11:20:39 +00:00
|
|
|
|
2021-02-26 09:33:11 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2019-01-07 11:20:39 +00:00
|
|
|
from radiusauth.backends import RADIUSBackend, RADIUSRealmBackend
|
|
|
|
from django.conf import settings
|
|
|
|
|
2022-02-25 11:23:59 +00:00
|
|
|
from .base import JMSBaseAuthBackend
|
|
|
|
|
2019-11-11 12:10:49 +00:00
|
|
|
|
2019-01-07 11:20:39 +00:00
|
|
|
User = get_user_model()
|
|
|
|
|
|
|
|
|
|
|
|
class CreateUserMixin:
|
2022-04-13 12:24:56 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_django_user(username, password=None, *args, **kwargs):
|
2019-01-07 11:20:39 +00:00
|
|
|
if isinstance(username, bytes):
|
|
|
|
username = username.decode()
|
2022-04-13 12:24:56 +00:00
|
|
|
user = User.objects.filter(username=username).first()
|
|
|
|
if user:
|
|
|
|
return user
|
|
|
|
|
|
|
|
if '@' in username:
|
|
|
|
email = username
|
|
|
|
else:
|
|
|
|
email_suffix = settings.EMAIL_SUFFIX
|
|
|
|
email = '{}@{}'.format(username, email_suffix)
|
|
|
|
|
|
|
|
user = User(username=username, name=username, email=email)
|
|
|
|
user.source = user.Source.radius.value
|
|
|
|
user.save()
|
2019-01-07 11:20:39 +00:00
|
|
|
return user
|
|
|
|
|
2020-07-31 11:40:27 +00:00
|
|
|
def _perform_radius_auth(self, client, packet):
|
|
|
|
# TODO: 等待官方库修复这个BUG
|
|
|
|
try:
|
|
|
|
return super()._perform_radius_auth(client, packet)
|
|
|
|
except UnicodeError as e:
|
|
|
|
import sys
|
|
|
|
tb = ''.join(traceback.format_exception(*sys.exc_info(), limit=2, chain=False))
|
|
|
|
if tb.find("cl.decode") != -1:
|
|
|
|
return [], False, False
|
|
|
|
return None
|
|
|
|
|
2019-01-07 11:20:39 +00:00
|
|
|
|
2022-02-25 11:23:59 +00:00
|
|
|
class RadiusBaseBackend(CreateUserMixin, JMSBaseAuthBackend):
|
|
|
|
@staticmethod
|
|
|
|
def is_enabled():
|
|
|
|
return settings.AUTH_RADIUS
|
|
|
|
|
|
|
|
|
|
|
|
class RadiusBackend(RadiusBaseBackend, RADIUSBackend):
|
2020-09-16 03:05:52 +00:00
|
|
|
def authenticate(self, request, username='', password='', **kwargs):
|
2020-09-16 02:52:50 +00:00
|
|
|
return super().authenticate(request, username=username, password=password)
|
2019-01-07 11:20:39 +00:00
|
|
|
|
|
|
|
|
2022-02-25 11:23:59 +00:00
|
|
|
class RadiusRealmBackend(RadiusBaseBackend, RADIUSRealmBackend):
|
2020-09-16 03:05:52 +00:00
|
|
|
def authenticate(self, request, username='', password='', realm=None, **kwargs):
|
2020-09-16 02:52:50 +00:00
|
|
|
return super().authenticate(request, username=username, password=password, realm=realm)
|