package com.example.sjkbf.config.exception;

import cn.hutool.log.StaticLog;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        // 默认处理，实际应由全局异常处理器接管
        // 设置响应状态码和内容类型
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");

        // 构建自定义错误信息
        Map<String, Object> errorData = new HashMap<>();
        errorData.put("code", 4010);
        errorData.put("msg", "此页面需要登录后访问");

        // 写入 JSON 响应
        response.getWriter().write(new ObjectMapper().writeValueAsString(errorData));
    }
}