package cn.reghao.bnt.web.admin.security;

import cn.reghao.jutil.web.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 在 WebSecurityConfig 中配置的需要认证的接口没有获取到请求中的认证信息时会转到此处进行处理
 *
 * @author reghao
 * @date 2023-07-28 16:43:59
 */
@Slf4j
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        String uri = request.getRequestURI();
        log.error("请求 {} 接口认证失败...", uri);

        /*String body = String.format("%s, %s need authenticate", exception.getMessage(), uri);
        response.sendRedirect("/bg/login");*/

        String body = String.format("%s, %s need authenticate", exception.getMessage(), uri);
        String retJson = WebResult.failWithMsg(body);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(retJson);
    }
}
