package cn.service.auth;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import cn.common.enums.ResultCode;
import cn.common.page.response.Result;
import cn.util.core.ServletKit;
import cn.util.string.StringKit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * 参数 request 是遇到了认证异常 authException 用户请求，response 是
 * 将要返回给客户的相应，方法 commence 实现，也就是相应的认证方案逻辑会修
 * 改 response 并返回给用户引导用户进入认证流程。
 */
@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 {
		/**
		 *  原来的 返回给浏览器一个400错误的HTTP页面；
		 */
		int code = ResultCode.HTTP_UNAUTHORIZED.getCode();
		//TooManyDevicesException CredentialsChangedException
		if (e instanceof BadCredentialsException) { 
			 code = ResultCode.HTTP_BAD_REQUEST.getCode();
	    } 
		String msg = StringKit.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
		ServletKit.renderString(response, JSON.toJSONString(Result.error(code, msg)));
	}
}
