package com.lij.himeeter.framework.security.handle;

import com.alibaba.fastjson2.JSON;
import com.lij.himeeter.common.constant.HttpStatus;
import com.lij.himeeter.common.core.domain.AjaxResult;
import com.lij.himeeter.common.utils.ServletUtils;
import com.lij.himeeter.common.utils.StringUtils;
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 org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.Serializable;

/**
 * <pre>
 *
 * 文件名 :  AuthenticationEntryPointImpl
 * 创建时间 : 2025年01月02日 14:51
 *
 * 文件描述 : 认证失败处理类 返回未授权
 * </pre>
 *
 * @author Nobita
 * @version 1.0.0
 */

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = 1L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
