package cn.wise.sc.energy.power.plant.business.security;

import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

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

public class HttpStatusLoginFailureHandler implements AuthenticationFailureHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("text/html;charset=utf-8");
	    BaseResponse wrapper = null;
        if(exception.getMessage().equals("Bad credentials")){
	        wrapper = BaseResponse.errorMsg("密码错误");
        }else{
	        wrapper =BaseResponse.errorMsg(exception.getMessage());
        }
        response.getWriter().write(objectMapper.writeValueAsString(wrapper));
    }
}