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
|
|
|
|
|
2019-11-11 12:10:49 +00:00
|
|
|
|
2019-01-07 11:20:39 +00:00
|
|
|
User = get_user_model()
|
|
|
|
|
|
|
|
|
|
|
|
class CreateUserMixin:
|
2020-07-16 09:07:40 +00:00
|
|
|
def get_django_user(self, username, password=None, *args, **kwargs):
|
2019-01-07 11:20:39 +00:00
|
|
|
if isinstance(username, bytes):
|
|
|
|
username = username.decode()
|
|
|
|
try:
|
|
|
|
user = User.objects.get(username=username)
|
|
|
|
except User.DoesNotExist:
|
|
|
|
if '@' in username:
|
|
|
|
email = username
|
|
|
|
else:
|
|
|
|
email_suffix = settings.EMAIL_SUFFIX
|
|
|
|
email = '{}@{}'.format(username, email_suffix)
|
|
|
|
user = User(username=username, name=username, email=email)
|
2020-12-09 10:43:13 +00:00
|
|
|
user.source = user.Source.radius.value
|
2019-01-07 11:20:39 +00:00
|
|
|
user.save()
|
|
|
|
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
|
|
|
|
|
|
|
class RadiusBackend(CreateUserMixin, 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
|
|
|
|
|
|
|
|
|
|
|
class RadiusRealmBackend(CreateUserMixin, 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)
|