Cloudreve/middleware/session.go

35 lines
1.1 KiB
Go
Raw Normal View History

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"
"github.com/HFO4/cloudreve/pkg/util"
2019-11-11 06:13:17 -05:00
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"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-29 02:24:23 -05:00
var Store memstore.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 {
// Redis设置不为空且非测试模式时使用Redis
2019-11-29 02:24:23 -05:00
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 {
2019-11-29 02:24:23 -05:00
util.Log().Panic("无法连接到 Redis%s", err)
2019-11-27 06:53:39 -05:00
}
2019-11-29 02:24:23 -05:00
util.Log().Info("已连接到 Redis 服务器:%s", conf.RedisConfig.Server)
2019-11-27 06:53:39 -05:00
} else {
Store = memstore.NewStore([]byte(secret))
}
2019-11-28 08:21:46 -05:00
2019-11-12 02:34:54 -05:00
// Also set Secure: true if using SSL, you should though
2019-11-30 02:09:56 -05:00
// TODO:same-site policy
2019-11-12 02:34:54 -05:00
Store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"})
return sessions.Sessions("cloudreve-session", Store)
2019-11-11 06:13:17 -05:00
}