package com.test.bijihoudaun.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.bijihoudaun.common.response.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;


import java.io.IOException;

/**
 * 自定义认证失败处理器
 * 当用户尝试访问受保护的资源而未提供有效凭证时（例如token无效或过期），此处理器被调用。
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
       // 设置响应字符编码为UTF-8，确保中文正确显示
       response.setCharacterEncoding("UTF-8");
       // 设置响应内容类型为JSON格式
       response.setContentType("application/json");
       // 设置HTTP状态码为401，表示未授权
       response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
       
       // 创建一个包含中文错误信息的R对象，R可能是自定义的响应结果封装类
       R<String> result = R.fail("认证失败，请重新登录");

       // 使用ObjectMapper将对象转换为JSON字符串并写入响应
       ObjectMapper objectMapper = new ObjectMapper();
       response.getWriter().write(objectMapper.writeValueAsString(result));
   }
}