package cn.reghao.bnt.web.admin.security.handler;

import cn.reghao.bnt.web.admin.security.exception.AccountLoginException;
import cn.reghao.bnt.web.admin.service.LoginAttemptService;
import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.web.WebResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证失败后的处理
 *
 * @author reghao
 * @date 2022-07-08 14:02:34
 */
@Component
public class AuthFailureHandlerImpl implements AuthenticationFailureHandler {
    private final LoginAttemptService loginAttemptService;

    public AuthFailureHandlerImpl(LoginAttemptService loginAttemptService) {
        this.loginAttemptService = loginAttemptService;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        String errMsg = exception.getMessage();
        if (exception instanceof AccountLoginException) {
            AccountLoginException ex = (AccountLoginException) exception;
            int userId = ex.getUserId();
            String loginId = ex.getLoginId();
            Result result = loginAttemptService.loginFailedCount(userId, loginId);
            if (result.getCode() != 0) {
                errMsg = result.getMsg();
            }
        }

        String body = WebResult.failWithMsg(errMsg);
        writeResponse(response, body);
    }

    private void writeResponse(HttpServletResponse response, String body) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(body);
    }
}
