package com.njzscloud.common.security.handler;

import com.njzscloud.common.core.ex.ExceptionMsg;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.core.utils.Mime;
import com.njzscloud.common.core.utils.R;
import com.njzscloud.common.mvc.util.ServletUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;


/**
 * 认证异常
 */
@Slf4j
public class AuthExceptionHandler implements AuthenticationEntryPoint {
    public static final AuthExceptionHandler INSTANCE = new AuthExceptionHandler();

    private AuthExceptionHandler() {
    }

    @Override
    public void commence(
        HttpServletRequest request,
        HttpServletResponse response,
        AuthenticationException authException
    ) throws IOException, ServletException {
        log.error("未登录: {}", request.getRequestURI(), authException);
        R<?> r;
        if (authException instanceof AuthenticationCredentialsNotFoundException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            r = R.failed(ExceptionMsg.CLI_ERR_MSG, "登录凭证无效");
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            r = R.failed(ExceptionMsg.SYS_ERR_MSG, "无法进行用户校验");
        }
        ServletUtil.write(response, Jackson.toJsonStr(r), Mime.u8Val(Mime.JSON));
    }
}
