from django.http import JsonResponse
from django.contrib.auth import authenticate
from functools import wraps


def api_user_auth(view_func):
    """
    API专用用户认证装饰器
    使用查询字符串参数: ?user=username&password=password
    验证失败返回JSON错误信息
    """

    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        # 从查询字符串获取认证信息
        username = request.GET.get('username')
        password = request.GET.get('password')

        # 检查参数完整性
        if not username or not password:
            return JsonResponse(
                {
                    'code': 400,
                    'error': '缺少认证参数',
                    'message': '请提供username和password查询参数'
                },
                status=400,
                json_dumps_params={'ensure_ascii': False},  # 禁用ASCII转义
                content_type='application/json; charset=utf-8')

        # 用户认证
        user = authenticate(request, username=username, password=password)

        if user is not None:
            # 认证成功，将用户信息添加到request中
            request.authenticated_user = user
            request.auth_username = username
            return view_func(request, *args, **kwargs)
        else:
            # 认证失败
            return JsonResponse(
                {
                    'code': 401,
                    'error': '认证失败',
                    'message': '用户名或密码错误'
                },
                status=401,
                json_dumps_params={'ensure_ascii': False},  # 禁用ASCII转义
                content_type='application/json; charset=utf-8')

    return wrapper
