2019-02-26 04:38:20 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
|
|
|
|
import json
|
2020-09-07 12:33:44 +00:00
|
|
|
import threading
|
2020-04-29 09:04:48 +00:00
|
|
|
from collections.abc import Iterable
|
2019-10-21 09:02:16 +00:00
|
|
|
from smtplib import SMTPSenderRefused
|
2019-05-29 02:11:58 +00:00
|
|
|
from rest_framework import generics
|
2019-03-22 07:55:46 +00:00
|
|
|
from rest_framework.views import Response, APIView
|
|
|
|
from django.conf import settings
|
2020-04-14 11:40:56 +00:00
|
|
|
from django.core.mail import send_mail, get_connection
|
2019-02-26 04:38:20 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2020-04-29 10:10:42 +00:00
|
|
|
from rest_framework import serializers
|
2019-02-26 04:38:20 +00:00
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
from .utils import (
|
|
|
|
LDAPServerUtil, LDAPCacheUtil, LDAPImportUtil, LDAPSyncUtil,
|
2020-04-29 03:08:09 +00:00
|
|
|
LDAP_USE_CACHE_FLAGS, LDAPTestUtil, ObjectDict
|
2019-11-11 08:41:32 +00:00
|
|
|
)
|
2020-09-07 12:33:44 +00:00
|
|
|
from .tasks import sync_ldap_user
|
2019-03-22 07:55:46 +00:00
|
|
|
from common.permissions import IsOrgAdmin, IsSuperUser
|
2019-03-28 04:50:04 +00:00
|
|
|
from common.utils import get_logger
|
2019-11-06 03:57:00 +00:00
|
|
|
from .serializers import (
|
2020-03-12 08:24:38 +00:00
|
|
|
MailTestSerializer, LDAPTestConfigSerializer, LDAPUserSerializer,
|
2020-04-29 09:04:48 +00:00
|
|
|
PublicSettingSerializer, LDAPTestLoginSerializer, SettingsSerializer
|
2019-11-06 03:57:00 +00:00
|
|
|
)
|
2019-11-11 08:41:32 +00:00
|
|
|
from users.models import User
|
2019-02-26 04:38:20 +00:00
|
|
|
|
2019-03-28 04:50:04 +00:00
|
|
|
logger = get_logger(__file__)
|
|
|
|
|
|
|
|
|
2019-02-26 04:38:20 +00:00
|
|
|
class MailTestingAPI(APIView):
|
2019-11-11 09:54:28 +00:00
|
|
|
permission_classes = (IsSuperUser,)
|
2019-02-26 04:38:20 +00:00
|
|
|
serializer_class = MailTestSerializer
|
|
|
|
success_message = _("Test mail sent to {}, please check")
|
|
|
|
|
|
|
|
def post(self, request):
|
|
|
|
serializer = self.serializer_class(data=request.data)
|
|
|
|
if serializer.is_valid():
|
2020-04-14 11:40:56 +00:00
|
|
|
email_host = serializer.validated_data['EMAIL_HOST']
|
|
|
|
email_port = serializer.validated_data['EMAIL_PORT']
|
|
|
|
email_host_user = serializer.validated_data["EMAIL_HOST_USER"]
|
|
|
|
email_host_password = serializer.validated_data['EMAIL_HOST_PASSWORD']
|
2019-06-14 02:51:18 +00:00
|
|
|
email_from = serializer.validated_data["EMAIL_FROM"]
|
2019-10-08 09:14:33 +00:00
|
|
|
email_recipient = serializer.validated_data["EMAIL_RECIPIENT"]
|
2020-04-14 11:40:56 +00:00
|
|
|
email_use_ssl = serializer.validated_data['EMAIL_USE_SSL']
|
|
|
|
email_use_tls = serializer.validated_data['EMAIL_USE_TLS']
|
|
|
|
|
|
|
|
# 设置 settings 的值,会导致动态配置在当前进程失效
|
|
|
|
# for k, v in serializer.validated_data.items():
|
|
|
|
# if k.startswith('EMAIL'):
|
|
|
|
# setattr(settings, k, v)
|
2019-02-26 04:38:20 +00:00
|
|
|
try:
|
|
|
|
subject = "Test"
|
|
|
|
message = "Test smtp setting"
|
2019-06-14 02:51:18 +00:00
|
|
|
email_from = email_from or email_host_user
|
2019-10-08 09:14:33 +00:00
|
|
|
email_recipient = email_recipient or email_from
|
2020-04-14 11:40:56 +00:00
|
|
|
connection = get_connection(
|
|
|
|
host=email_host, port=email_port,
|
2020-06-04 08:47:43 +00:00
|
|
|
username=email_host_user, password=email_host_password,
|
2020-04-14 11:40:56 +00:00
|
|
|
use_tls=email_use_tls, use_ssl=email_use_ssl,
|
|
|
|
)
|
|
|
|
send_mail(
|
2020-04-29 03:08:09 +00:00
|
|
|
subject, message, email_from, [email_recipient],
|
2020-04-14 11:40:56 +00:00
|
|
|
connection=connection
|
|
|
|
)
|
2019-10-21 09:02:16 +00:00
|
|
|
except SMTPSenderRefused as e:
|
|
|
|
resp = e.smtp_error
|
|
|
|
if isinstance(resp, bytes):
|
|
|
|
for coding in ('gbk', 'utf8'):
|
|
|
|
try:
|
|
|
|
resp = resp.decode(coding)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
break
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({"error": str(resp)}, status=400)
|
2019-02-26 04:38:20 +00:00
|
|
|
except Exception as e:
|
2019-10-21 09:02:16 +00:00
|
|
|
print(e)
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({"error": str(e)}, status=400)
|
2019-10-08 09:14:33 +00:00
|
|
|
return Response({"msg": self.success_message.format(email_recipient)})
|
2019-02-26 04:38:20 +00:00
|
|
|
else:
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({"error": str(serializer.errors)}, status=400)
|
2019-02-26 04:38:20 +00:00
|
|
|
|
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
class LDAPTestingConfigAPI(APIView):
|
2019-11-11 09:54:28 +00:00
|
|
|
permission_classes = (IsSuperUser,)
|
2020-03-12 08:24:38 +00:00
|
|
|
serializer_class = LDAPTestConfigSerializer
|
|
|
|
|
|
|
|
def post(self, request):
|
|
|
|
serializer = self.serializer_class(data=request.data)
|
|
|
|
if not serializer.is_valid():
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({"error": str(serializer.errors)}, status=400)
|
2020-03-12 08:24:38 +00:00
|
|
|
config = self.get_ldap_config(serializer)
|
|
|
|
ok, msg = LDAPTestUtil(config).test_config()
|
2020-05-07 08:57:57 +00:00
|
|
|
status = 200 if ok else 400
|
2020-03-12 08:24:38 +00:00
|
|
|
return Response(msg, status=status)
|
2019-02-26 04:38:20 +00:00
|
|
|
|
2019-03-28 04:50:04 +00:00
|
|
|
@staticmethod
|
2019-11-11 08:41:32 +00:00
|
|
|
def get_ldap_config(serializer):
|
|
|
|
server_uri = serializer.validated_data["AUTH_LDAP_SERVER_URI"]
|
2019-03-28 04:50:04 +00:00
|
|
|
bind_dn = serializer.validated_data["AUTH_LDAP_BIND_DN"]
|
|
|
|
password = serializer.validated_data["AUTH_LDAP_BIND_PASSWORD"]
|
|
|
|
use_ssl = serializer.validated_data.get("AUTH_LDAP_START_TLS", False)
|
2020-03-12 08:24:38 +00:00
|
|
|
search_ou = serializer.validated_data["AUTH_LDAP_SEARCH_OU"]
|
2019-03-28 04:50:04 +00:00
|
|
|
search_filter = serializer.validated_data["AUTH_LDAP_SEARCH_FILTER"]
|
|
|
|
attr_map = serializer.validated_data["AUTH_LDAP_USER_ATTR_MAP"]
|
2020-03-12 08:24:38 +00:00
|
|
|
auth_ldap = serializer.validated_data.get('AUTH_LDAP', False)
|
2019-11-11 08:41:32 +00:00
|
|
|
config = {
|
|
|
|
'server_uri': server_uri,
|
|
|
|
'bind_dn': bind_dn,
|
|
|
|
'password': password,
|
|
|
|
'use_ssl': use_ssl,
|
2020-03-12 08:24:38 +00:00
|
|
|
'search_ou': search_ou,
|
2019-11-11 08:41:32 +00:00
|
|
|
'search_filter': search_filter,
|
2020-03-12 08:24:38 +00:00
|
|
|
'attr_map': attr_map,
|
|
|
|
'auth_ldap': auth_ldap
|
2019-11-11 08:41:32 +00:00
|
|
|
}
|
|
|
|
return config
|
2019-03-28 04:50:04 +00:00
|
|
|
|
2020-03-12 08:24:38 +00:00
|
|
|
|
|
|
|
class LDAPTestingLoginAPI(APIView):
|
|
|
|
permission_classes = (IsSuperUser,)
|
|
|
|
serializer_class = LDAPTestLoginSerializer
|
|
|
|
|
2019-02-26 04:38:20 +00:00
|
|
|
def post(self, request):
|
|
|
|
serializer = self.serializer_class(data=request.data)
|
2019-03-28 04:50:04 +00:00
|
|
|
if not serializer.is_valid():
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({"error": str(serializer.errors)}, status=400)
|
2020-03-12 08:24:38 +00:00
|
|
|
username = serializer.validated_data['username']
|
|
|
|
password = serializer.validated_data['password']
|
|
|
|
ok, msg = LDAPTestUtil().test_login(username, password)
|
2020-05-07 08:57:57 +00:00
|
|
|
status = 200 if ok else 400
|
2020-03-12 08:24:38 +00:00
|
|
|
return Response(msg, status=status)
|
2019-02-26 04:38:20 +00:00
|
|
|
|
|
|
|
|
2019-05-29 02:11:58 +00:00
|
|
|
class LDAPUserListApi(generics.ListAPIView):
|
2019-11-11 09:54:28 +00:00
|
|
|
permission_classes = (IsSuperUser,)
|
2019-08-21 12:27:21 +00:00
|
|
|
serializer_class = LDAPUserSerializer
|
2019-03-22 07:55:46 +00:00
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
def get_queryset_from_cache(self):
|
|
|
|
search_value = self.request.query_params.get('search')
|
|
|
|
users = LDAPCacheUtil().search(search_value=search_value)
|
|
|
|
return users
|
|
|
|
|
|
|
|
def get_queryset_from_server(self):
|
|
|
|
search_value = self.request.query_params.get('search')
|
|
|
|
users = LDAPServerUtil().search(search_value=search_value)
|
|
|
|
return users
|
|
|
|
|
2019-05-29 02:11:58 +00:00
|
|
|
def get_queryset(self):
|
2019-09-18 14:06:46 +00:00
|
|
|
if hasattr(self, 'swagger_fake_view'):
|
|
|
|
return []
|
2019-11-11 08:41:32 +00:00
|
|
|
cache_police = self.request.query_params.get('cache_police', True)
|
|
|
|
if cache_police in LDAP_USE_CACHE_FLAGS:
|
|
|
|
users = self.get_queryset_from_cache()
|
|
|
|
else:
|
|
|
|
users = self.get_queryset_from_server()
|
2019-05-29 02:11:58 +00:00
|
|
|
return users
|
|
|
|
|
2019-11-11 09:45:39 +00:00
|
|
|
@staticmethod
|
|
|
|
def processing_queryset(queryset):
|
|
|
|
db_username_list = User.objects.all().values_list('username', flat=True)
|
|
|
|
for q in queryset:
|
|
|
|
q['id'] = q['username']
|
|
|
|
q['existing'] = q['username'] in db_username_list
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
def sort_queryset(self, queryset):
|
|
|
|
order_by = self.request.query_params.get('order')
|
|
|
|
if not order_by:
|
|
|
|
order_by = 'existing'
|
|
|
|
if order_by.startswith('-'):
|
|
|
|
order_by = order_by.lstrip('-')
|
|
|
|
reverse = True
|
|
|
|
else:
|
|
|
|
reverse = False
|
|
|
|
queryset = sorted(queryset, key=lambda x: x[order_by], reverse=reverse)
|
|
|
|
return queryset
|
|
|
|
|
|
|
|
def filter_queryset(self, queryset):
|
|
|
|
if queryset is None:
|
|
|
|
return queryset
|
|
|
|
queryset = self.processing_queryset(queryset)
|
|
|
|
queryset = self.sort_queryset(queryset)
|
|
|
|
return queryset
|
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
def list(self, request, *args, **kwargs):
|
|
|
|
cache_police = self.request.query_params.get('cache_police', True)
|
|
|
|
# 不是用缓存
|
|
|
|
if cache_police not in LDAP_USE_CACHE_FLAGS:
|
|
|
|
return super().list(request, *args, **kwargs)
|
|
|
|
|
2019-11-11 09:45:39 +00:00
|
|
|
try:
|
|
|
|
queryset = self.get_queryset()
|
|
|
|
except Exception as e:
|
|
|
|
data = {'error': str(e)}
|
|
|
|
return Response(data=data, status=400)
|
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
# 缓存有数据
|
|
|
|
if queryset is not None:
|
|
|
|
return super().list(request, *args, **kwargs)
|
|
|
|
|
|
|
|
sync_util = LDAPSyncUtil()
|
|
|
|
# 还没有同步任务
|
|
|
|
if sync_util.task_no_start:
|
2019-11-13 07:08:54 +00:00
|
|
|
# 任务外部设置 task running 状态
|
|
|
|
sync_util.set_task_status(sync_util.TASK_STATUS_IS_RUNNING)
|
2020-09-07 12:33:44 +00:00
|
|
|
t = threading.Thread(target=sync_ldap_user)
|
|
|
|
t.start()
|
|
|
|
data = {'msg': 'Sync start.'}
|
2019-11-11 08:41:32 +00:00
|
|
|
return Response(data=data, status=409)
|
|
|
|
# 同步任务正在执行
|
|
|
|
if sync_util.task_is_running:
|
|
|
|
data = {'msg': 'synchronization is running.'}
|
|
|
|
return Response(data=data, status=409)
|
|
|
|
# 同步任务执行结束
|
|
|
|
if sync_util.task_is_over:
|
|
|
|
msg = sync_util.get_task_error_msg()
|
2020-09-07 12:33:44 +00:00
|
|
|
data = {'error': 'Synchronization error: {}'.format(msg)}
|
2019-11-11 08:41:32 +00:00
|
|
|
return Response(data=data, status=400)
|
|
|
|
|
|
|
|
return super().list(request, *args, **kwargs)
|
|
|
|
|
2019-03-22 07:55:46 +00:00
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
class LDAPUserImportAPI(APIView):
|
2019-11-11 09:54:28 +00:00
|
|
|
permission_classes = (IsSuperUser,)
|
2019-03-22 07:55:46 +00:00
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
def get_ldap_users(self):
|
|
|
|
username_list = self.request.data.get('username_list', [])
|
|
|
|
cache_police = self.request.query_params.get('cache_police', True)
|
|
|
|
if cache_police in LDAP_USE_CACHE_FLAGS:
|
|
|
|
users = LDAPCacheUtil().search(search_users=username_list)
|
|
|
|
else:
|
|
|
|
users = LDAPServerUtil().search(search_users=username_list)
|
|
|
|
return users
|
|
|
|
|
2019-03-22 07:55:46 +00:00
|
|
|
def post(self, request):
|
2019-11-11 09:45:39 +00:00
|
|
|
try:
|
|
|
|
users = self.get_ldap_users()
|
|
|
|
except Exception as e:
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({'error': str(e)}, status=400)
|
2019-11-11 09:45:39 +00:00
|
|
|
|
|
|
|
if users is None:
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({'msg': _('Get ldap users is None')}, status=400)
|
2019-11-11 09:45:39 +00:00
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
errors = LDAPImportUtil().perform_import(users)
|
|
|
|
if errors:
|
2020-05-07 08:57:57 +00:00
|
|
|
return Response({'errors': errors}, status=400)
|
2019-11-11 09:45:39 +00:00
|
|
|
|
|
|
|
count = users if users is None else len(users)
|
2019-11-11 10:15:25 +00:00
|
|
|
return Response({'msg': _('Imported {} users successfully').format(count)})
|
2019-11-11 08:41:32 +00:00
|
|
|
|
2019-03-28 04:50:04 +00:00
|
|
|
|
2019-11-11 08:41:32 +00:00
|
|
|
class LDAPCacheRefreshAPI(generics.RetrieveAPIView):
|
2019-11-11 09:54:28 +00:00
|
|
|
permission_classes = (IsSuperUser,)
|
2019-11-11 08:41:32 +00:00
|
|
|
|
|
|
|
def retrieve(self, request, *args, **kwargs):
|
2019-03-28 04:50:04 +00:00
|
|
|
try:
|
2019-11-11 08:41:32 +00:00
|
|
|
LDAPSyncUtil().clear_cache()
|
2019-03-28 04:50:04 +00:00
|
|
|
except Exception as e:
|
2019-11-11 08:41:32 +00:00
|
|
|
logger.error(str(e))
|
|
|
|
return Response(data={'msg': str(e)}, status=400)
|
|
|
|
return Response(data={'msg': 'success'})
|
2019-03-22 07:55:46 +00:00
|
|
|
|
|
|
|
|
2019-11-06 03:57:00 +00:00
|
|
|
class PublicSettingApi(generics.RetrieveAPIView):
|
|
|
|
permission_classes = ()
|
|
|
|
serializer_class = PublicSettingSerializer
|
|
|
|
|
|
|
|
def get_object(self):
|
|
|
|
instance = {
|
|
|
|
"data": {
|
2020-02-26 08:12:08 +00:00
|
|
|
"WINDOWS_SKIP_ALL_MANUAL_PASSWORD": settings.WINDOWS_SKIP_ALL_MANUAL_PASSWORD,
|
|
|
|
"SECURITY_MAX_IDLE_TIME": settings.SECURITY_MAX_IDLE_TIME,
|
2020-05-18 06:55:16 +00:00
|
|
|
"XPACK_ENABLED": settings.XPACK_ENABLED,
|
2020-06-08 08:48:10 +00:00
|
|
|
"XPACK_LICENSE_IS_VALID": settings.XPACK_LICENSE_IS_VALID,
|
2020-06-09 02:17:16 +00:00
|
|
|
"LOGIN_CONFIRM_ENABLE": settings.LOGIN_CONFIRM_ENABLE,
|
|
|
|
"SECURITY_VIEW_AUTH_NEED_MFA": settings.SECURITY_VIEW_AUTH_NEED_MFA,
|
2020-06-09 06:06:11 +00:00
|
|
|
"SECURITY_MFA_VERIFY_TTL": settings.SECURITY_MFA_VERIFY_TTL,
|
2020-06-17 07:03:41 +00:00
|
|
|
"SECURITY_COMMAND_EXECUTION": settings.SECURITY_COMMAND_EXECUTION,
|
2020-09-27 03:34:59 +00:00
|
|
|
"LOGIN_TITLE": settings.XPACK_INTERFACE_LOGIN_TITLE,
|
2020-06-16 03:04:59 +00:00
|
|
|
"LOGO_URLS": settings.LOGO_URLS,
|
2020-09-14 06:02:11 +00:00
|
|
|
"TICKETS_ENABLED": settings.TICKETS_ENABLED,
|
2020-06-16 03:04:59 +00:00
|
|
|
"PASSWORD_RULE": {
|
|
|
|
'SECURITY_PASSWORD_MIN_LENGTH': settings.SECURITY_PASSWORD_MIN_LENGTH,
|
|
|
|
'SECURITY_PASSWORD_UPPER_CASE': settings.SECURITY_PASSWORD_UPPER_CASE,
|
|
|
|
'SECURITY_PASSWORD_LOWER_CASE': settings.SECURITY_PASSWORD_LOWER_CASE,
|
|
|
|
'SECURITY_PASSWORD_NUMBER': settings.SECURITY_PASSWORD_NUMBER,
|
|
|
|
'SECURITY_PASSWORD_SPECIAL_CHAR': settings.SECURITY_PASSWORD_SPECIAL_CHAR,
|
|
|
|
}
|
2019-11-06 03:57:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return instance
|
|
|
|
|
|
|
|
|
2020-04-29 09:04:48 +00:00
|
|
|
class SettingsApi(generics.RetrieveUpdateAPIView):
|
2020-05-07 08:57:57 +00:00
|
|
|
permission_classes = (IsSuperUser,)
|
2020-04-29 09:04:48 +00:00
|
|
|
serializer_class = SettingsSerializer
|
2020-04-29 03:08:09 +00:00
|
|
|
|
2020-04-29 09:04:48 +00:00
|
|
|
def get_object(self):
|
2020-04-29 10:10:42 +00:00
|
|
|
instance = {category: self._get_setting_fields_obj(list(category_serializer.get_fields()))
|
|
|
|
for category, category_serializer in self.serializer_class().get_fields().items()
|
|
|
|
if isinstance(category_serializer, serializers.Serializer)}
|
2020-04-29 09:04:48 +00:00
|
|
|
return ObjectDict(instance)
|
2020-04-29 03:08:09 +00:00
|
|
|
|
2020-04-29 09:04:48 +00:00
|
|
|
def perform_update(self, serializer):
|
|
|
|
serializer.save()
|
2020-04-29 03:08:09 +00:00
|
|
|
|
2020-04-29 09:04:48 +00:00
|
|
|
def _get_setting_fields_obj(self, category_fields):
|
|
|
|
if isinstance(category_fields, Iterable):
|
|
|
|
fields_data = {field_name: getattr(settings, field_name)
|
|
|
|
for field_name in category_fields}
|
|
|
|
return ObjectDict(fields_data)
|
2020-04-29 03:08:09 +00:00
|
|
|
|
2020-04-29 09:04:48 +00:00
|
|
|
if isinstance(category_fields, str):
|
|
|
|
fields_data = {category_fields: getattr(settings, category_fields)}
|
|
|
|
return ObjectDict(fields_data)
|
2020-04-29 03:08:09 +00:00
|
|
|
|
2020-04-29 09:04:48 +00:00
|
|
|
return ObjectDict()
|