package com.app.admin.framework.system.permission.shiro.service.impl;

import com.app.admin.framework.system.permission.shiro.realm.ShiroRealm;
import com.app.admin.framework.system.permission.shiro.service.ShiroCacheManagerService;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Shiro缓存管理
 */
@Service
public class ShiroCacheManagerServiceImpl implements ShiroCacheManagerService {

    @Autowired
    MemoryConstrainedCacheManager shiroCacheManager;
    @Autowired
    DefaultWebSecurityManager securityManager;

    /**
     * 清除缓存
     * @param users 用户名集合
     */
    public void destroy(List<String> users){
        Cache<Object, Object> cache  = shiroCacheManager.getCache("com.app.admin.framework.system.permission.shiro.realm.ShiroRealm.authorizationCache");
        if(cache != null && users != null){
            int size = users.size();
            for (int i = 0; i < size; i++) {
                String username = users.get(i);
                SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(username, username);
                cache.remove(principalCollection);
            }
        }
    }

    /**
     * 删除登陆人对应的缓存
     * @param username 登录名
     */
    public void clearShiroCache(String username){
        ShiroRealm shiroRealm = (ShiroRealm)securityManager.getRealms().iterator().next();
        SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(username, username);
        //删除登陆人缓存
        shiroRealm.getAuthorizationCache().remove(principalCollection);
    }

}
