package com.cool.bang.core.secure.process;

import com.cool.bang.common.tools.servlet.ServletUtil;
import com.cool.bang.common.web.response.Result;
import com.cool.bang.modules.system.mapper.UserMapper;
import com.xiaoleilu.hutool.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义 spring security 用户登录失败处理类
 *
 * @author PeiZhi Guo
 * 2021-2-18 14:51
 */
@Component
public class SecurityAccessFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException {
        // 默认提示
        Result res = Result.failure(
                HttpStatus.HTTP_OK, "未知错误，请联系管理员");

        if (e instanceof UsernameNotFoundException) {
            res.setMsg(e.getMessage());
        }
        else if (e instanceof AccountExpiredException) {
            res.setMsg("账户已超期，如有疑问请联系管理员");
        }
        else if (e instanceof LockedException) {
            res.setMsg("账户已锁定，如有疑问请联系管理员");
        }
        else if (e instanceof BadCredentialsException) {
            res.setMsg(e.getMessage());
        }
        else if (e instanceof DisabledException) {
            res.setMsg("账户已禁用，如有疑问请联系管理员");
        }

        ServletUtil.jsonWrite(res, HttpStatus.HTTP_OK);
    }
}
