Cloudreve/middleware/session.go

57 lines
1.6 KiB
Go
Raw Normal View History

2019-11-11 19:13:17 +08:00
package middleware
import (
"github.com/cloudreve/Cloudreve/v3/pkg/conf"
"github.com/cloudreve/Cloudreve/v3/pkg/serializer"
"github.com/cloudreve/Cloudreve/v3/pkg/util"
2019-11-11 19:13:17 +08:00
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-contrib/sessions/redis"
2019-11-11 19:13:17 +08:00
"github.com/gin-gonic/gin"
)
2019-11-12 15:34:54 +08:00
// Store session存储
2019-11-29 15:24:23 +08:00
var Store memstore.Store
2019-11-12 15:34:54 +08:00
2019-11-11 19:13:17 +08:00
// Session 初始化session
func Session(secret string) gin.HandlerFunc {
// Redis设置不为空且非测试模式时使用Redis
2019-11-29 15:24:23 +08:00
if conf.RedisConfig.Server != "" && gin.Mode() != gin.TestMode {
2019-11-27 19:53:39 +08:00
var err error
Store, err = redis.NewStoreWithDB(10, conf.RedisConfig.Network, conf.RedisConfig.Server, conf.RedisConfig.Password, conf.RedisConfig.DB, []byte(secret))
2019-11-27 19:53:39 +08:00
if err != nil {
2019-11-29 15:24:23 +08:00
util.Log().Panic("无法连接到 Redis%s", err)
2019-11-27 19:53:39 +08:00
}
2019-11-29 15:24:23 +08:00
util.Log().Info("已连接到 Redis 服务器:%s", conf.RedisConfig.Server)
2019-11-27 19:53:39 +08:00
} else {
Store = memstore.NewStore([]byte(secret))
}
2019-11-28 21:21:46 +08:00
2019-11-12 15:34:54 +08:00
// Also set Secure: true if using SSL, you should though
2019-11-30 15:09:56 +08:00
// TODO:same-site policy
2019-11-12 15:34:54 +08:00
Store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"})
return sessions.Sessions("cloudreve-session", Store)
2019-11-11 19:13:17 +08:00
}
// CSRFInit 初始化CSRF标记
func CSRFInit() gin.HandlerFunc {
return func(c *gin.Context) {
util.SetSession(c, map[string]interface{}{"CSRF": true})
c.Next()
}
}
// CSRFCheck 检查CSRF标记
func CSRFCheck() gin.HandlerFunc {
return func(c *gin.Context) {
if check, ok := util.GetSession(c, "CSRF").(bool); ok && check {
c.Next()
return
}
c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, "来源非法", nil))
c.Abort()
}
}