package com.changfa.config.shiro;

import com.changfa.config.RedisConfig;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;

import javax.servlet.Filter;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author wwz
 * shiro配置
 */
public class ShiroConfig {

    @Value("${shiro.ignoreAll}")
    private boolean ignoreAll;

    @Autowired
    private ShiroProperties shiroProperties;
    @Autowired
    private RedisConfig.ByteRedisTemplate redisTemplate;
    @Autowired
    @Qualifier(value = "redisTemplate")
    private RedisTemplate stringRedisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(ShiroConfig.class);

    /**
     * 设置session会话过期时间为两小时
     */
    private static final Integer expireTime = 3600 * 2;

    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

    //将自己的验证方式加入容器
    @Bean
    public CustomRealm myShiroRealm() {
        CustomRealm customRealm = new CustomRealm();
        return customRealm;
    }

    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis
     * SessionDAO的作用是为Session提供CRUD并进行持久化的一个shiro组件
     * MemorySessionDAO 直接在内存中进行会话维护
     * EnterpriseCacheSessionDAO  提供了缓存功能的会话维护，默认情况下使用MapCache实现，内部使用ConcurrentHashMap保存缓存的会话。
     */
    @Bean
    public CustomRedisSessionDAO redisSessionDAO() {
        CustomRedisSessionDAO redisSessionDAO = new CustomRedisSessionDAO();
        redisSessionDAO.setRedisTemplate(redisTemplate);
        redisSessionDAO.setStringRedisTemplate(stringRedisTemplate);
        redisSessionDAO.setRedisManager(redisManager);
        redisSessionDAO.setExpire(expireTime);
        redisSessionDAO.setSessionIdGenerator(new CustomSessionIdGenerator());
        return redisSessionDAO;
    }

    class CustomSessionIdGenerator implements SessionIdGenerator {
        public CustomSessionIdGenerator(){

        }

        @Override
        public Serializable generateId(Session session) {
            return Base64Utils.encodeToString(UUID.randomUUID().toString().toUpperCase().replaceAll("-","").getBytes()).toUpperCase();
        }
    }


    /**
     * sessionManager = session管理
     * @return
     */
    @Bean
    public SessionManager sessionManager() {
        MySessionManager mySessionManager = new MySessionManager();
        mySessionManager.setSessionDAO(redisSessionDAO());
        mySessionManager.setSessionIdCookieEnabled(false);
        mySessionManager.setSessionIdUrlRewritingEnabled(false);
        //mySessionManager.setGlobalSessionTimeout(-1000);
        return mySessionManager;
    }
    /**
     * 配置shiro redisManager
     * <p>
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.redis")
    public RedisManager redisManager() {
        RedisManager  redisManager = new RedisManager();
        return redisManager;
    }


    @Autowired
    RedisManager redisManager;
    /**
     * cacheManager 缓存 redis实现
     * <p>
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager);
        redisCacheManager.setExpire(expireTime);
        return redisCacheManager;
    }

    @Autowired
    RedisCacheManager redisCacheManager;
    //权限管理，配置主要是Realm的管理认证
    @Bean
    public  SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        securityManager.setSessionManager(sessionManager());
        securityManager.setCacheManager(redisCacheManager);
        securityManager.setRememberMeManager(null);
        return securityManager;
    }


    @Autowired
    private  SecurityManager securityManager;
    //Filter工厂，设置对应的过滤条件和跳转条件
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        logger.info("==============初始化shiro================");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String,Filter> filterMap = shiroFilterFactoryBean.getFilters();
        filterMap.put("authc",new ShiroLoginFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        Map<String, String> map = new LinkedHashMap<>();
        //登录
        //shiroFilterFactoryBean.setLoginUrl("/loginPage");
        //首页
        //错误页面，认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
        //登出
        //对所有用户认证
        if(!ignoreAll){
           List<String> ignoreAuthc =  shiroProperties.getIgnoreAuthc();
            if(!ObjectUtils.isEmpty(ignoreAuthc)){
                ignoreAuthc.stream().forEach(item->{
                    map.put(item,"anon");
                });
            }
            map.put("/**", "authc");
        }else{
            map.put("/**", "anon");
        }
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }


    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean
    public ProxyTransactionManagementConfiguration proxyTransactionManagementConfiguration(){
        return new ProxyTransactionManagementConfiguration();
    }


    public boolean getIgnoreAll() {
        return ignoreAll;
    }

    public void setIgnoreAll(boolean ignoreAll) {
        this.ignoreAll = ignoreAll;
    }

}
