package com.yiboshi.science.config.security;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.ForwardLogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author qyh
 * 退出登录后清除token
 */
public class UserLogoutSuccessHandler extends ForwardLogoutSuccessHandler {

    static Logger logger = LoggerFactory.getLogger(UserLogoutSuccessHandler.class);

    private TokenStore tokenStore;

    /**
     * Construct a new {@link ForwardLogoutSuccessHandler} with the given target URL.
     *
     * @param targetUrl the target URL
     */
    public UserLogoutSuccessHandler(String targetUrl,TokenStore tokenStore) {
        super(targetUrl);
        this.tokenStore=tokenStore;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String accessToken = request.getParameter("access_token");
        logger.info("清除token:" + accessToken);
        if (StrUtil.isNotBlank(accessToken)) {
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(accessToken);
            if (oAuth2AccessToken != null) {
                tokenStore.removeAccessToken(oAuth2AccessToken);
                OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();
                tokenStore.removeRefreshToken(oAuth2RefreshToken);
                tokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
            }
        }
        super.onLogoutSuccess(request, response, authentication);
    }
}
