package com.tuoheng.common.security.security;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tuoheng.common.security.utils.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
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;

@Component
public class OAuthAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
//        httpServletResponse.setContentType("application/json; charset=utf-8");
//        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Throwable cause = authException.getCause();
        try {
            if (cause instanceof InvalidTokenException) {
                // 无效的token
                JsonResult jsonResult = new JsonResult();
                response.getWriter().write(JSONObject.toJSONString(jsonResult.error(401, "请先登录"), SerializerFeature.WriteMapNullValue));
            } else {
                // 访问此资源需要完全的身份验证
                JsonResult jsonResult = new JsonResult();
                response.getWriter().write(JSONObject.toJSONString(jsonResult.error(401, "访问此资源需要完全的身份验证"), SerializerFeature.WriteMapNullValue));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
