package cn.estsh.i3plus.core.apiservice.auth;

import cn.estsh.i3plus.core.apiservice.auth.realm.AdminAuthRealm;
import cn.estsh.i3plus.core.apiservice.auth.realm.DefaultModularRealm;
import cn.estsh.i3plus.core.apiservice.auth.realm.SaAuthRealm;
import cn.estsh.i3plus.core.apiservice.auth.realm.UserAuthRealm;
import cn.estsh.i3plus.platform.common.util.CommonConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.impp.framework.boot.auth.filter.AdminFilter;
import cn.estsh.impp.framework.boot.auth.filter.SaAdminFilter;
import cn.estsh.impp.framework.boot.auth.filter.UserFilter;
import cn.estsh.impp.framework.boot.configuration.RedisConfig;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description : shiro权限配置
 * @Reference :
 * @Author : alwaysfrin
 * @CreateDate : 2018-10-13 18:25
 * @Modify:
 **/
@Configuration
@AutoConfigureAfter(RedisConfig.class)       //2类配置，延后加载
public class ShiroAuthConfiguration {
    public static final Logger LOGGER = LoggerFactory.getLogger(CommonConstWords.SYSTEM_LOG);

    @Value("${filter.shiro.admin.loginuri}")
    private String adminLoginUri;

    @Value("${filter.shiro.admin.filteruri}")
    private String adminFilterUri;

    @Value("${filter.shiro.saadmin.loginuri}")
    private String saAdminLoginUri;

    @Value("${filter.shiro.saadmin.filteruri}")
    private String saAdminFilterUri;

    @Value("${filter.shiro.user.loginuri}")
    private String userLoginUri;

    @Value("${filter.shiro.user.filteruri}")
    private String userFilterUri;

    //平台控制缓存
    @Resource(name = "imppSessionEhCacheManager")
    private CacheManager getEhCacheManage;

    //平台控制会话
    @Resource(name = "imppSessionManager")
    private DefaultWebSessionManager getSessionManage;

    @Bean
    public AdminAuthRealm adminAuthRealm(){
        return new AdminAuthRealm();
    }

    @Bean
    public SaAuthRealm saAuthRealm(){
        return new SaAuthRealm();
    }

    @Bean
    public UserAuthRealm userAuthRealm(){
        return new UserAuthRealm();
    }

    public Map<String,Realm> supportRealmMap(){
        //支持的授权规则
        Map<String,Realm> realms = new HashMap();
        realms.put(CommonEnumUtil.USER_TYPE.USER.getCode(),userAuthRealm());
        realms.put(CommonEnumUtil.USER_TYPE.ADMIN.getCode(),adminAuthRealm());
        realms.put(CommonEnumUtil.USER_TYPE.SA.getCode(),saAuthRealm());

        return realms;
    }

    @Bean
    public ModularRealmAuthenticator modularRealmAuthenticator(){
        return  new DefaultModularRealm(supportRealmMap());
    }

    @Bean
    public SecurityManager securityManager(){
        LOGGER.info("【app-shiro-加载securityManager】");
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        securityManager.setAuthenticator(modularRealmAuthenticator());
        securityManager.setRealms(supportRealmMap().values());
        securityManager.setCacheManager(getEhCacheManage);    //缓存管理
        securityManager.setSessionManager(getSessionManage);  //会话管理
        //securityManager.setRememberMeManager(getRememberManager());
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        Map<String, Filter> filterMap = new HashMap();
        filterMap.put("user_filter", new UserFilter());
        filterMap.put("admin_filter", new AdminFilter());
        filterMap.put("saadmin_filter", new SaAdminFilter());
        factoryBean.setFilters(filterMap);

        Map<String, String> filterChain = new LinkedHashMap();
        //不需要过滤的路径，直接通过
        filterChain.put(userLoginUri, "anon");
        filterChain.put(adminLoginUri, "anon");
        filterChain.put(saAdminLoginUri, "anon");

        //需要过滤的路径
        filterChain.put(userFilterUri, "user_filter");
        filterChain.put(adminFilterUri, "admin_filter");
        filterChain.put(saAdminFilterUri, "saadmin_filter");

        factoryBean.setFilterChainDefinitionMap(filterChain);

        LOGGER.info("【app-shiro授权过滤】加载完成...");
        return factoryBean;
    }

        /** 缓存等配置在impp平台中设置 **/
//    /**
//     * 缓存管理
//     * @return
//     */
//    @Bean(name = "ehCacheManager")
//    public CacheManager getEhCacheManage() {
//        LOGGER.info("【shiro-加载缓存cacheManager】");
//        EhCacheManager em = new EhCacheManager();
//        em.setCacheManagerConfigFile("classpath:cache_session.xml");
//        return em;
//    }
//
//    @Bean(name = "sessionManager")
//    public DefaultWebSessionManager getSessionManage() {
//        LOGGER.info("【shiro-加载sessionManager】");
//        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
//        sessionManager.setSessionValidationScheduler(getExecutorServiceSessionValidationScheduler());
//        sessionManager.setSessionValidationSchedulerEnabled(true);
//        sessionManager.setDeleteInvalidSessions(true);
//        sessionManager.setSessionIdCookieEnabled(true);
//        sessionManager.setSessionIdCookie(getSessionIdCookie());
//        sessionManager.setSessionDAO(getShiroSessionRedisDaoImpl());
//        sessionManager.setGlobalSessionTimeout(30 * 60 * 1000); //30分钟有效期(以sessionDao中的有效时间为准)
//
//        // 可以添加session 创建、删除的监听器
//        return sessionManager;
//    }
//
//    @Bean
//    public ShiroSessionRedisDaoImpl getShiroSessionRedisDaoImpl(){
//        LOGGER.info("【shiro-加载缓存redisSessionManager】");
//        ShiroSessionRedisDaoImpl shiroSessionRedisDao = new ShiroSessionRedisDaoImpl();
//
//        LOGGER.info("【shiro-加载缓存cacheManager】");
//        shiroSessionRedisDao.setLocalCacheManager(getEhCacheManage() );
//        return shiroSessionRedisDao;
//    }
//
//    /**
//     * 授权验证监听任务
//     * @return
//     */
//    @Bean(name = "sessionValidationScheduler")
//    public ExecutorServiceSessionValidationScheduler getExecutorServiceSessionValidationScheduler() {
//        LOGGER.info("【shiro-加载sessionValidationScheduler】");
//        ExecutorServiceSessionValidationScheduler scheduler = new ExecutorServiceSessionValidationScheduler();
//        scheduler.setInterval(3 * 60 * 1000);   //每3分钟执行一次验证
//        return scheduler;
//    }
//
//    @Bean(name = "sessionIdCookie")
//    public SimpleCookie getSessionIdCookie() {
//        LOGGER.info("【shiro-加载sessionIdCookie】");
//        SimpleCookie cookie = new SimpleCookie("sid");
//        cookie.setHttpOnly(true);
//        cookie.setMaxAge(-1);
//
//        return cookie;
//    }
}
