package cn.reghao.oss.console.account.security.handler;

import cn.reghao.jutil.jdk.result.WebResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

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

/**
 * 认证失败后的处理
 *
 * @author reghao
 * @date 2019-04-09 00:02:34
 */
@Component
public class AuthFailHandlerImpl implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        String errMsg = exception.getMessage();
        String body = WebResult.failWithMsg(errMsg);
        writeResponse(response, body);
    }

    private void writeResponse(HttpServletResponse response, String body) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(body);
    }
}
