package cn.reghao.tnb.auth.app.security.handler;

import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.auth.app.security.exception.AccountLoginException;
import cn.reghao.tnb.auth.app.service.LoginAttemptService;
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;
            long userId = ex.getUserId();
            String loginId = ex.getLoginId();
            Result result = loginAttemptService.loginFailedCount(userId, loginId);
            if (result.getCode() != 0) {
                errMsg = result.getMsg();
            }
        }
        loginFailed(response, errMsg);
    }

    public void loginFailed(HttpServletResponse response, String errMsg) throws IOException {
        String retJson = WebResult.failWithMsg(errMsg);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(retJson);
    }
}
