package com.tykj.dev.device.user.util;

import com.tykj.dev.device.user.subject.entity.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zjm
 */
@Service
public class LogoutUtil {
    @Autowired
    SessionRegistry sessionRegistry;

    public void logout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication!=null) {
            if (authentication.getPrincipal().equals("anonymousUser")){
                return;
            }
            SecurityUser user = (SecurityUser) authentication.getPrincipal();
            List<Object> o = sessionRegistry.getAllPrincipals();
            for (Object principal : o) {
                SecurityUser cacheUser = (SecurityUser) principal;
                if (cacheUser.getUsername().equals(user.getUsername())) {
                    List<SessionInformation> sessions = sessionRegistry.getAllSessions(cacheUser, true);
                    for (SessionInformation sessionInformation : sessions) {
                        sessionInformation.expireNow();
                    }
                }
            }
            SecurityContextHolder.clearContext();
        }
    }
}
