package com.keao.edu.auth.core.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.keao.edu.common.entity.HttpResponseResult;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class BaseAuthenticationFailureEvenHandler extends ExceptionMappingAuthenticationFailureHandler {

    private final static Logger logger = LoggerFactory.getLogger(BaseAuthenticationFailureEvenHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
    	
    	int resultCode = HttpStatus.SC_CONFLICT;
    	
        String message = exception.getLocalizedMessage();
        if (message.equals("Bad credentials")) {
            message = "用户名或密码错误";
        }else if(message.equals("User is disabled")){
            message = "账户被锁定";
        }else if(message.equals("404.9")){
        	message = "用户名或密码错误";
        	resultCode = 99;
        }
        logger.info("登录失败，异常：{}", message);
        HttpResponseResult result = new HttpResponseResult(false, resultCode, null, message);
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
