package com.ningdatech.pmapi.user.security.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningdatech.basic.model.ApiResponse;
import com.ningdatech.pmapi.user.security.auth.errorcode.AuthErrorCodeEnum;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

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

/**
 * @Author LiuXinXin
 * @Date 2020/8/3 8:32 下午
 * @Version 1.0
 **/
@Component("defaultLoginFailureHandler")
public class DefaultLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        int errorCode;
        String errorMsg;
        // 所有的认证异常都可以在这里添加，目前只支持用户名密码错误异常

        if (exception instanceof BadCredentialsException || exception instanceof UsernameNotFoundException) {
            errorCode = AuthErrorCodeEnum.USERNAME_OR_PASSWORD_ERROR.getCode();
            errorMsg = exception.getMessage();
        } else {
            errorCode = ApiResponse.ERROR_CODE;
            errorMsg = ApiResponse.ERROR_MSG;
        }
        response.setStatus(400);
        response.getWriter()
                .write(objectMapper.writeValueAsString(ApiResponse.of(errorCode, errorMsg, null)));
    }

}
