package com.starry.admin.common.security.handler;

import com.alibaba.fastjson2.JSON;
import com.starry.admin.common.component.JwtToken;
import com.starry.admin.common.security.entity.JwtUser;
import com.starry.admin.manager.AsyncManager;
import com.starry.admin.manager.factory.AsyncFactory;
import com.starry.common.constant.Constants;
import com.starry.common.result.R;
import com.starry.common.utils.ServletUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * @author admin 自定义退出处理类 返回成功
 * @since 2022/7/8
 */
@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private JwtToken jwtToken;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
            Authentication authentication) {
        JwtUser jwtUser = jwtToken.getLoginUser(httpServletRequest);
        if (null != jwtUser) {
            // 删除用户缓存记录
            jwtToken.removeJwtUser(jwtUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLoginLog(jwtUser.getUsername(), Constants.LOGOUT, "退出成功"));
        }
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(R.ok("退出成功")));
    }
}
