package com.tykj.dev.device.user.config.handler;

import lombok.extern.slf4j.Slf4j;
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;

/**
 * @author zjm
 */
@Component
@Slf4j
public class MyFailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.error("[登录模块] 登录发生异常 : {}",e.getMessage());
        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json");
        if (e.getMessage().equals("Bad credentials")){
            httpServletResponse.getWriter().println("{\"code\":401,\"msg\":\"密码错误请重新输入\"}");
        }else {
            httpServletResponse.getWriter().println("{\"code\":401,\"msg\":\"" + e.getMessage() + "\"}");
        }
    }
}
