package org.lingniu.idp.security.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.lingniu.idp.constant.Constants;
import org.lingniu.idp.manager.AsyncManager;
import org.lingniu.idp.manager.factory.AsyncFactory;
import org.lingniu.idp.model.base.AjaxResult;
import org.lingniu.idp.model.vo.RefreshTokenInfo;
import org.lingniu.idp.service.core.login.IdpTokenService;
import org.lingniu.idp.utils.MessageUtils;
import org.lingniu.idp.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author portal
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Autowired
    private IdpTokenService idpTokenService;

    /**
     * 退出处理
     * 
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException, ServletException
    {
        RefreshTokenInfo refreshTokenInfo = idpTokenService.getRefreshTokenInfo(request);
        idpTokenService.revokeToken(request,response);
        if (refreshTokenInfo!=null)
        {
            String userName = refreshTokenInfo.getUsername();
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
    }
}
