package com.ningdatech.carapi.user.security.auth.config;

import cn.hutool.core.util.StrUtil;
import com.ningdatech.basic.util.StrPool;
import com.ningdatech.carapi.common.constant.CommonConstant;
import com.ningdatech.carapi.user.security.auth.constant.SessionTimeConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.RedisIndexedSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.DefaultCookieSerializer;

/**
 * <p>
 * 设置session的过期时间为一天
 * </p>
 *
 * @Author LiuXinXin
 * @Date 2020/7/29 9:46 上午
 * @Version 1.0
 **/
@Configuration
@EnableRedisHttpSession(
        maxInactiveIntervalInSeconds = RedisSessionConfig.SESSION_TIMEOUT,
        redisNamespace = RedisSessionConfig.REDIS_NAMESPACE
)
public class RedisSessionConfig {

    static final int SESSION_TIMEOUT = 24 * 60 * 60 * 10;

    static final String REDIS_NAMESPACE = "#{redisSessionConfig.getRedisNamespace()}";

    @Value("${nd.cache.def.keyPrefix:}")
    private String keyPrefix;

    public String getRedisNamespace() {
        return (StrUtil.isBlank(keyPrefix) ? StrPool.EMPTY : keyPrefix + StrPool.COLON) + RedisIndexedSessionRepository.DEFAULT_NAMESPACE;
    }


    @Bean
    public CookieHttpSessionIdResolver sessionIdResolver() {
        // 创建 CookieHttpSessionIdResolver 对象
        CookieHttpSessionIdResolver sessionIdResolver = new CookieHttpSessionIdResolver();

        // 创建 DefaultCookieSerializer 对象
        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();

        // 设置到 sessionIdResolver 中
        sessionIdResolver.setCookieSerializer(cookieSerializer);
        cookieSerializer.setCookieName(CommonConstant.COOKIE_KEY);
        cookieSerializer.setCookieMaxAge(SessionTimeConstant.SESSION_TIME_SECONDS);
        return sessionIdResolver;
    }
}
