package com.skr.mdm.authentication.admin;

import com.skr.mdm.enums.ResultCodeEnum;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
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 nfq
 * @date 2020/7/17 10:54
 */
@Slf4j
@Component
public class AdminAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        ResponseResult result = ResponseResult.failure(ResultCodeEnum.LOGIN_FAILURE);
        if (exception instanceof BadCredentialsException) {
            result = ResponseResult.failure(ResultCodeEnum.LOGIN_FAILURE);
        }
        if (exception instanceof InternalAuthenticationServiceException) {
            if (exception.getCause() instanceof BlockedAccountException) {
                result = ResponseResult.failure(ResultCodeEnum.BLOCKED_ACCOUNT);
            }
        }
        ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), result);
    }
}
