package com.easyproject.core.security.handle;

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

import com.easyproject.common.core.domain.model.LoginMember;
import com.easyproject.core.web.service.MemberTokenService;
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 com.alibaba.fastjson2.JSON;
import com.easyproject.common.constant.Constants;
import com.easyproject.common.core.domain.AjaxClientResult;
import com.easyproject.common.utils.ServletUtils;
import com.easyproject.common.utils.StringUtils;
import com.easyproject.core.manager.AsyncManager;
import com.easyproject.core.manager.factory.AsyncFactory;

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

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginMember loginMember = tokenService.getLoginMember(request);
        if (StringUtils.isNotNull(loginMember))
        {
            String userName = loginMember.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginMember.getToken(), loginMember.getId());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxClientResult.success("退出成功")));
    }
}
