2019-11-11 06:13:17 -05:00
|
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
2019-11-27 06:53:39 -05:00
|
|
|
|
"github.com/HFO4/cloudreve/pkg/conf"
|
2019-11-27 06:14:13 -05:00
|
|
|
|
"github.com/HFO4/cloudreve/pkg/util"
|
2019-11-11 06:13:17 -05:00
|
|
|
|
"github.com/gin-contrib/sessions"
|
2019-11-12 00:55:33 -05:00
|
|
|
|
"github.com/gin-contrib/sessions/memstore"
|
2019-11-27 06:14:13 -05:00
|
|
|
|
"github.com/gin-contrib/sessions/redis"
|
2019-11-11 06:13:17 -05:00
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
2019-11-12 02:34:54 -05:00
|
|
|
|
// Store session存储
|
2019-11-27 06:53:39 -05:00
|
|
|
|
var Store redis.Store
|
2019-11-12 02:34:54 -05:00
|
|
|
|
|
2019-11-11 06:13:17 -05:00
|
|
|
|
// Session 初始化session
|
|
|
|
|
func Session(secret string) gin.HandlerFunc {
|
2019-11-27 08:53:07 -05:00
|
|
|
|
// Redis设置不为空,且非测试模式时使用Redis
|
|
|
|
|
if conf.RedisConfig.Server != "" && gin.Mode() == gin.TestMode {
|
2019-11-27 06:53:39 -05:00
|
|
|
|
var err error
|
|
|
|
|
Store, err = redis.NewStoreWithDB(10, "tcp", conf.RedisConfig.Server, conf.RedisConfig.Password, conf.RedisConfig.DB, []byte(secret))
|
|
|
|
|
if err != nil {
|
|
|
|
|
util.Log().Panic("无法连接到Redis:%s", err)
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
Store = memstore.NewStore([]byte(secret))
|
2019-11-27 06:14:13 -05:00
|
|
|
|
}
|
2019-11-12 02:34:54 -05:00
|
|
|
|
// Also set Secure: true if using SSL, you should though
|
|
|
|
|
Store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"})
|
|
|
|
|
return sessions.Sessions("cloudreve-session", Store)
|
2019-11-11 06:13:17 -05:00
|
|
|
|
}
|