package com.njzscloud.common.security.handler;

import com.njzscloud.common.core.ex.ExceptionMsg;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.core.utils.Mime;
import com.njzscloud.common.core.utils.R;
import com.njzscloud.common.mvc.util.ServletUtil;
import com.njzscloud.common.security.support.Token;
import com.njzscloud.common.security.support.UserAuthenticationToken;
import com.njzscloud.common.security.util.SecurityUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

/**
 * 退出登陆处理器
 */
public class LogoutPostHandler implements LogoutSuccessHandler, LogoutHandler {

    /**
     * 退出登陆
     */
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        UserAuthenticationToken userAuthenticationToken = (UserAuthenticationToken) authentication;
        Token token = (Token) userAuthenticationToken.getCredentials();
        SecurityUtil.removeToken(token);
    }

    /**
     * 退出登陆成功
     */
    @Override
    public void onLogoutSuccess(
        HttpServletRequest request,
        HttpServletResponse response,
        Authentication authentication
    ) throws IOException, ServletException {
        R<Boolean> r;
        if (authentication == null) {
            r = R.failed(Boolean.FALSE, ExceptionMsg.CLI_ERR_MSG, "未登陆，无需操作");
        } else {
            r = R.success(Boolean.TRUE);
        }
        ServletUtil.write(response, Jackson.toJsonStr(r), Mime.u8Val(Mime.JSON));
    }


}
