package com.ningdatech.kqapi.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningdatech.basic.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 登录失败处理器
 * </p>
 *
 * @author WendyYang
 * @since 00:11 2023/3/2
 */
@Slf4j
@Primary
@Component
public class DefaultLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private final ObjectMapper objectMapper;

    public DefaultLoginFailureHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException e) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ApiResponse<Void> apiRet;
        // 所有的认证异常都可以在这里添加，目前只支持用户名密码错误异常
        if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
            apiRet = ApiResponse.of(ApiResponse.ERROR_CODE, e.getMessage());
        } else {
            apiRet = ApiResponse.of(ApiResponse.ERROR_CODE, "登录失败，请联系管理员");
        }

        response.setStatus(HttpStatus.OK.value());
        response.getWriter().write(objectMapper.writeValueAsString(apiRet));
    }

}
