package cn.teammodel.security.handler;

import cn.hutool.json.JSONUtil;
import cn.teammodel.common.ErrorCode;
import cn.teammodel.common.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author winter
 * @date 2022年11月26日 下午4:51
 * @description 定义验证失败的处理器，子类实现
 */
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control","no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(errorMsg());
        response.getWriter().flush();
    }
    public Object errorMsg() {
        return JSONUtil.parse(R.error(ErrorCode.NO_AUTH_ERROR));
    }
}