package com.qiaoba.auth.handler;

import com.qiaoba.auth.entity.LoginUser;
import com.qiaoba.auth.service.OnlineUserService;
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;
import java.util.Objects;

/**
 * 退出处理器
 *
 * @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 {
        // 删除缓存中的用户信息
        LoginUser user = (LoginUser) authentication.getPrincipal();
        onlineUserService.deleteOne(user.getUsername(), user.getDeviceSn(), true);
    }
}
