package com.zjty.tynotes.pas.utils;

import com.zjty.tynotes.pas.entity.User;
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 mcj
 */
@Service
public class LogoutUtil {
    @Autowired
    SessionRegistry sessionRegistry;

    public void logout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();

        List<Object> o = sessionRegistry.getAllPrincipals();
        for ( Object principal : o) {
            User cacheUser = (User)principal;
            if (cacheUser.getUsername().equals(user.getUsername())) {
                List<SessionInformation> sessions = sessionRegistry.getAllSessions(cacheUser, true);
                for (SessionInformation sessionInformation : sessions) {
                    sessionInformation.expireNow();
                }
            }
        }
        SecurityContextHolder.clearContext();
    }
}
