package com.ai.da.common.security;

import com.ai.da.common.response.Response;
import com.ai.da.common.response.ResultEnum;
import com.ai.da.common.utils.JSONResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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;

/**
 * @ClassName UserLoginFailureHandler
 * @Description 登录失败处理类
 * @Author dwjian
 * @Date 2020/7/9 20:17
 */
@Slf4j
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Response<String> response;
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            response = Response.fail(e.getMessage());
        } else if (e instanceof LockedException) {
            response = Response.fail(ResultEnum.ACCOUNT_LOCK);
        } else if (e instanceof CredentialsExpiredException) {
            response = Response.fail("证书过期，请联系管理员!");
        } else if (e instanceof AccountExpiredException) {
            response = Response.fail("账户过期，请联系管理员!");
        } else if (e instanceof DisabledException) {
            response = Response.fail("账户被禁用，请联系管理员!");
        } else if (e instanceof AuthenticationServiceException) {
            response = Response.fail(e.getMessage());
        } else {
            log.error("登录失败：", e);
            response = Response.fail("登录失败!");
        }
        JSONResponseUtils.build(httpServletResponse, response);
    }
}
