2026-10-22 06:48:00 +00:00
|
|
|
|
# coding=utf-8
|
|
|
|
|
|
"""用户管理扩展序列化器:待激活审核、角色授权。"""
|
|
|
|
|
|
from django.core.cache import cache
|
|
|
|
|
|
from django.core.mail import send_mail
|
|
|
|
|
|
from django.core.mail.backends.smtp import EmailBackend
|
|
|
|
|
|
from django.db import transaction
|
|
|
|
|
|
from django.db.models import Q
|
|
|
|
|
|
from django.utils import timezone
|
|
|
|
|
|
from rest_framework import serializers
|
|
|
|
|
|
|
|
|
|
|
|
from common.constants.cache_version import Cache_Version
|
|
|
|
|
|
from common.constants.permission_constants import RoleConstants
|
|
|
|
|
|
from common.exception.app_exception import AppApiException
|
|
|
|
|
|
from common.utils.logger import maxkb_logger
|
|
|
|
|
|
from system_manage.models import SystemSetting, SettingType
|
|
|
|
|
|
from users.models import User, UserActivationApplication, ActivationStatus, UserRoleAssignment
|
|
|
|
|
|
|
|
|
|
|
|
ROLE_OPTIONS = [
|
|
|
|
|
|
{"id": RoleConstants.USER.name, "name": "普通用户"},
|
|
|
|
|
|
{"id": RoleConstants.ADMIN.name, "name": "管理员"},
|
|
|
|
|
|
]
|
|
|
|
|
|
VALID_ROLE_IDS = {item["id"] for item in ROLE_OPTIONS}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _fmt(value):
|
|
|
|
|
|
if not value:
|
|
|
|
|
|
return ""
|
|
|
|
|
|
try:
|
|
|
|
|
|
value = timezone.localtime(value)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
return value.strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def invalidate_user_auth_cache(user_id):
|
|
|
|
|
|
"""角色/状态变化后清掉权限与角色缓存,下一次请求重新计算。"""
|
|
|
|
|
|
for cache_version in (Cache_Version.PERMISSION_LIST, Cache_Version.ROLE_LIST, Cache_Version.USER):
|
|
|
|
|
|
cache.delete(cache_version.get_key(user_id=user_id), version=cache_version.get_version())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def send_activation_notice(user, approved: bool, reason: str = "") -> bool:
|
|
|
|
|
|
"""激活审核结果邮件通知。
|
|
|
|
|
|
|
|
|
|
|
|
仅在系统设置中配置了发件邮箱(SystemSetting EMAIL)且用户填了邮箱时发送;
|
|
|
|
|
|
发送失败只记录日志,不影响审核结果。
|
|
|
|
|
|
"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
if not user.email:
|
|
|
|
|
|
return False
|
|
|
|
|
|
setting = SystemSetting.objects.filter(type=SettingType.EMAIL.value).first()
|
|
|
|
|
|
meta = (setting.meta or {}) if setting else {}
|
|
|
|
|
|
if not meta.get("email_host"):
|
|
|
|
|
|
return False
|
|
|
|
|
|
name = user.nick_name or user.username
|
|
|
|
|
|
if approved:
|
|
|
|
|
|
subject = "【AI-RAG 知识库平台】账号激活审核通过"
|
|
|
|
|
|
body = (f"您好 {name}:\n\n"
|
|
|
|
|
|
f"您提交的注册申请已审核通过,账号已激活,现在可以登录平台使用。\n\n"
|
|
|
|
|
|
f"如非本人操作,请忽略本邮件。")
|
|
|
|
|
|
else:
|
|
|
|
|
|
subject = "【AI-RAG 知识库平台】账号激活审核未通过"
|
|
|
|
|
|
body = (f"您好 {name}:\n\n"
|
|
|
|
|
|
f"很抱歉,您提交的注册申请未通过审核。\n"
|
|
|
|
|
|
f"拒绝原因:{reason or '不符合激活条件'}\n\n"
|
|
|
|
|
|
f"请在注册页面使用原用户名和密码修改并重新提交资料,审核通过后即可登录。")
|
|
|
|
|
|
connection = EmailBackend(meta.get("email_host"), meta.get("email_port"),
|
|
|
|
|
|
meta.get("email_host_user"), meta.get("email_host_password"),
|
|
|
|
|
|
meta.get("email_use_tls"), False, meta.get("email_use_ssl"), timeout=10)
|
|
|
|
|
|
send_mail(subject, body,
|
|
|
|
|
|
from_email=meta.get("from_email") or meta.get("email_host_user"),
|
|
|
|
|
|
recipient_list=[user.email],
|
|
|
|
|
|
fail_silently=False, connection=connection)
|
|
|
|
|
|
return True
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
maxkb_logger.error(f"send activation notice failed: user={getattr(user, 'id', '')} {exc}")
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ActivationSerializer(serializers.Serializer):
|
|
|
|
|
|
keyword = serializers.CharField(required=False, allow_blank=True, default="")
|
|
|
|
|
|
status = serializers.CharField(required=False, allow_blank=True, default=ActivationStatus.PENDING)
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def page(current_page: int, page_size: int, keyword: str = "", status: str = ActivationStatus.PENDING):
|
|
|
|
|
|
query_set = UserActivationApplication.objects.select_related("user").all()
|
|
|
|
|
|
if status == 'UNAPPROVED':
|
|
|
|
|
|
query_set = query_set.filter(status__in=[ActivationStatus.PENDING, ActivationStatus.REJECTED])
|
|
|
|
|
|
elif status and status != "ALL":
|
|
|
|
|
|
query_set = query_set.filter(status=status)
|
|
|
|
|
|
if keyword:
|
|
|
|
|
|
query_set = query_set.filter(
|
|
|
|
|
|
Q(user__username__icontains=keyword)
|
|
|
|
|
|
| Q(user__nick_name__icontains=keyword)
|
|
|
|
|
|
| Q(user__email__icontains=keyword)
|
|
|
|
|
|
| Q(user__phone__icontains=keyword)
|
|
|
|
|
|
)
|
|
|
|
|
|
total = query_set.count()
|
|
|
|
|
|
start = max(0, (current_page - 1) * page_size)
|
|
|
|
|
|
records = []
|
|
|
|
|
|
for application in query_set.order_by("-applied_at")[start:start + page_size]:
|
|
|
|
|
|
user = application.user
|
|
|
|
|
|
records.append({
|
|
|
|
|
|
"id": str(application.id),
|
|
|
|
|
|
"user_id": str(user.id),
|
|
|
|
|
|
"username": user.username,
|
|
|
|
|
|
"nick_name": user.nick_name,
|
|
|
|
|
|
"email": user.email or application.email or "",
|
|
|
|
|
|
"phone": user.phone or '',
|
|
|
|
|
|
"email_verified": application.email_verified,
|
|
|
|
|
|
"status": application.status,
|
|
|
|
|
|
"applied_at": _fmt(application.applied_at),
|
|
|
|
|
|
"audit_time": _fmt(application.audit_time),
|
|
|
|
|
|
"reject_reason": application.reject_reason,
|
|
|
|
|
|
})
|
|
|
|
|
|
return {"records": records, "total": total, "current_page": current_page, "page_size": page_size}
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
@transaction.atomic
|
|
|
|
|
|
def approve(application_id: str, audit_user_id: str, role_id: str = RoleConstants.USER.name,
|
|
|
|
|
|
workspace_id: str = "default"):
|
2026-10-27 02:54:52 +00:00
|
|
|
|
from system_manage.models.platform_access import PlatformRole
|
|
|
|
|
|
from system_manage.platform_access import ADMIN_ROLE_ID
|
|
|
|
|
|
PlatformRole.objects.select_for_update().get(pk=ADMIN_ROLE_ID)
|
2026-10-22 06:48:00 +00:00
|
|
|
|
application = (UserActivationApplication.objects.select_for_update()
|
|
|
|
|
|
.select_related("user").filter(id=application_id).first())
|
|
|
|
|
|
if application is None:
|
|
|
|
|
|
raise AppApiException(500, "待激活申请不存在")
|
|
|
|
|
|
if application.status != ActivationStatus.PENDING:
|
|
|
|
|
|
raise AppApiException(500, "该申请已处理,不能重复审核")
|
|
|
|
|
|
if role_id not in VALID_ROLE_IDS:
|
|
|
|
|
|
raise AppApiException(500, "角色不合法")
|
|
|
|
|
|
application.status = ActivationStatus.APPROVED
|
|
|
|
|
|
application.reject_reason = ""
|
|
|
|
|
|
application.audit_by_id = audit_user_id
|
|
|
|
|
|
application.audit_time = timezone.now()
|
|
|
|
|
|
application.save()
|
|
|
|
|
|
|
|
|
|
|
|
user = application.user
|
|
|
|
|
|
user.is_active = True
|
|
|
|
|
|
user.save()
|
2026-10-27 02:54:52 +00:00
|
|
|
|
from system_manage.platform_access import assign_legacy_role, require_admin
|
|
|
|
|
|
if role_id == RoleConstants.ADMIN.name:
|
|
|
|
|
|
require_admin(User.objects.get(pk=audit_user_id))
|
|
|
|
|
|
assign_legacy_role(user, role_id, audit_user_id)
|
2026-10-22 06:48:00 +00:00
|
|
|
|
invalidate_user_auth_cache(user.id)
|
|
|
|
|
|
transaction.on_commit(lambda: send_activation_notice(user, True))
|
|
|
|
|
|
return {"id": str(application.id), "status": application.status, "user_id": str(user.id)}
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
@transaction.atomic
|
|
|
|
|
|
def reject(application_id: str, audit_user_id: str, reason: str = ""):
|
|
|
|
|
|
application = (UserActivationApplication.objects.select_for_update()
|
|
|
|
|
|
.select_related("user").filter(id=application_id).first())
|
|
|
|
|
|
if application is None:
|
|
|
|
|
|
raise AppApiException(500, "待激活申请不存在")
|
|
|
|
|
|
if application.status != ActivationStatus.PENDING:
|
|
|
|
|
|
raise AppApiException(500, "该申请已处理,不能重复审核")
|
|
|
|
|
|
application.status = ActivationStatus.REJECTED
|
|
|
|
|
|
application.audit_by_id = audit_user_id
|
|
|
|
|
|
application.audit_time = timezone.now()
|
|
|
|
|
|
application.reject_reason = reason or "不符合激活条件"
|
|
|
|
|
|
application.save()
|
|
|
|
|
|
application.user.is_active = False
|
|
|
|
|
|
application.user.save()
|
|
|
|
|
|
invalidate_user_auth_cache(application.user.id)
|
|
|
|
|
|
transaction.on_commit(lambda: send_activation_notice(application.user, False, application.reject_reason))
|
|
|
|
|
|
return {"id": str(application.id), "status": application.status, "user_id": str(application.user_id)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RoleAssignmentSerializer(serializers.Serializer):
|
|
|
|
|
|
role_id = serializers.CharField(required=True)
|
|
|
|
|
|
workspace_ids = serializers.ListField(child=serializers.CharField(), required=False, allow_empty=True)
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def detail(user_id: str):
|
|
|
|
|
|
user = User.objects.filter(id=user_id).first()
|
|
|
|
|
|
if user is None:
|
|
|
|
|
|
raise AppApiException(500, "用户不存在")
|
2026-10-27 02:54:52 +00:00
|
|
|
|
from system_manage.platform_access import roles_for
|
|
|
|
|
|
from system_manage.models.platform_access import PlatformRole
|
|
|
|
|
|
records = [{'role_id': str(role.id), 'name': role.name, 'workspace_id': 'default', 'granted_at': ''} for role in roles_for(user)]
|
2026-10-22 06:48:00 +00:00
|
|
|
|
return {
|
|
|
|
|
|
"user": {"id": str(user.id), "username": user.username, "nick_name": user.nick_name,
|
|
|
|
|
|
"email": user.email or "", "role": user.role, "is_active": user.is_active},
|
|
|
|
|
|
"assignments": records,
|
2026-10-27 02:54:52 +00:00
|
|
|
|
"available_roles": [{'id': str(r.id), 'name': r.name} for r in PlatformRole.objects.order_by('created_at')],
|
2026-10-22 06:48:00 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
@transaction.atomic
|
|
|
|
|
|
def save(user_id: str, role_settings, granted_by_id: str):
|
2026-10-27 02:54:52 +00:00
|
|
|
|
user = User.objects.filter(id=user_id).first()
|
2026-10-22 06:48:00 +00:00
|
|
|
|
if user is None:
|
|
|
|
|
|
raise AppApiException(500, "用户不存在")
|
2026-10-27 02:54:52 +00:00
|
|
|
|
if not isinstance(role_settings, list) or not all(isinstance(item, dict) for item in role_settings):
|
2026-10-22 06:48:00 +00:00
|
|
|
|
raise AppApiException(500, '角色配置无效')
|
2026-10-27 02:54:52 +00:00
|
|
|
|
from system_manage.platform_access import assign_roles, assign_legacy_role, require_admin
|
|
|
|
|
|
require_admin(User.objects.get(pk=granted_by_id))
|
|
|
|
|
|
if any(item.get('workspace_ids') not in (None, [], ['default']) for item in role_settings):
|
|
|
|
|
|
raise AppApiException(500, '角色配置无效')
|
|
|
|
|
|
if len(role_settings) == 1 and role_settings[0].get('role_id') in VALID_ROLE_IDS:
|
|
|
|
|
|
assign_legacy_role(user, role_settings[0]['role_id'], granted_by_id)
|
|
|
|
|
|
else:
|
|
|
|
|
|
ids = serializers.ListField(child=serializers.UUIDField(), max_length=100).run_validation([item.get('role_id') for item in role_settings])
|
|
|
|
|
|
assign_roles(user.id, ids, granted_by_id)
|
2026-10-22 06:48:00 +00:00
|
|
|
|
return RoleAssignmentSerializer.detail(str(user.id))
|