package com.yiboshi.science.config.security;

import com.alibaba.fastjson.JSONObject;
import com.yiboshi.arch.base.ResponseCode;
import com.yiboshi.arch.base.ResponseDataModel;
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 AuthExceptionEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Throwable cause = authException.getCause();
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if(cause instanceof InvalidTokenException) {
                response.getWriter().write(JSONObject.toJSONString(new ResponseDataModel(ResponseCode.TOKEN_EXPIRATION.code(), "登录过期，TOKEN已失效","")));
            }else{
                response.getWriter().write(JSONObject.toJSONString(new ResponseDataModel(ResponseCode.PARAMETER_EXCEPTION.code(), "访问此资源需要完全的身份验证","")));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}