package com.ytpm.handle;

import com.alibaba.fastjson.JSONObject;
import com.ytpm.general.RepMessage;
import com.ytpm.general.StatusCode;
import lombok.extern.slf4j.Slf4j;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 客户端未授权的访问处理逻辑
 */
@Component
@Slf4j
public class AgentAuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        Throwable cause = authException.getCause();
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            JSONObject body = new JSONObject();
            body.put("code", StatusCode.MANAGE_NOT_LOGIN);
            body.put("message", RepMessage.TOKEN_EXPIRE);
            if (!(cause instanceof InvalidTokenException)) {
                body.put("code", StatusCode.MANAGE_NOT_LOGIN);
                body.put("message", RepMessage.TOKEN_INVALID);
            }
            response.getWriter().write(body.toJSONString());
        } catch (IOException e) {
            log.error("token认证失败={}", e);
        }
    }
}
