package com.qiaoba.auth.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.api.auth.entity.LoginUser;
import com.qiaoba.api.auth.entity.dto.OnlineUserDto;
import com.qiaoba.api.auth.service.OnlineUserService;
import com.qiaoba.api.auth.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

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

/**
 * 退出处理器
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022/1/4 0004 下午 16:20
 */
@Component
@RequiredArgsConstructor
public class LogoutHandler implements LogoutSuccessHandler {

    private final OnlineUserService onlineUserService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = TokenUtil.getToken(request, true);
        if (StrUtil.isNotBlank(token)) {
            try {
                // 删除缓存中的用户信息
                OnlineUserDto userDto = TokenUtil.getUsernameAndDeviceSn(token);
                onlineUserService.deleteOne(userDto.getUsername(), userDto.getDeviceSn(), true);
            } catch (Exception e) {

            }
        }
    }
}
