package com.system.oauth.config;

import com.system.framework.core.response.StarBosResult;
import com.system.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Oauth2异常信息返回处理
 *
 * @author ly_rical
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.error(e.getMessage());
        //如果是client_id和client_secret相关异常 返回自定义的数据格式
        if (e instanceof BadCredentialsException) {
            response.setStatus(HttpStatus.OK.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");

            StarBosResult<Boolean> result = StarBosResult.fail(912, "INVALID_CLIENT");
            result.setData(false);
            response.getWriter().write(JsonUtil.toString(result));
        } else if (e instanceof InsufficientAuthenticationException) {
            //如果是没有携带token
            InsufficientAuthenticationException a = (InsufficientAuthenticationException) e;
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            StarBosResult<Boolean> result = StarBosResult.fail(911, "未携带TOKEN或无效TOKEN");
            result.setData(false);
            response.getWriter().write(JsonUtil.toString(result));
        } else {
            super.commence(request, response, e);
        }
    }
}
