2 Star 0 Fork 0

TeamsHub/backend-gopkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
session.go 1.65 KB
一键复制 编辑 原始数据 按行查看 历史
HCY 提交于 2024-05-10 13:07 . edit pkg
package middleware
import (
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/config"
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/gin/log"
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/serializer"
"gitee.com/wuzheng0709/backend-gopkg/infrastructure/pkg/util"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-contrib/sessions/redis"
"github.com/gin-gonic/gin"
)
// Store session存储
var Store memstore.Store
// Session 初始化session
func Session(secret string) gin.HandlerFunc {
// Redis设置不为空,且非测试模式时使用Redis
if config.C.Redis.Host != "" && gin.Mode() != gin.TestMode {
var err error
Store, err = redis.NewStoreWithDB(10, "tcp", config.C.Redis.Host+":"+config.C.Redis.Port, config.C.Redis.Auth, "5", []byte(secret))
if err != nil {
log.Panic("无法连接到 Redis:%s", err)
}
log.Info("已连接到 Redis 服务器")
} else {
Store = memstore.NewStore([]byte(secret))
}
// Also set Secure: true if using SSL, you should though
// TODO:same-site policy
Store.Options(sessions.Options{HttpOnly: true, MaxAge: 30 * 3600, Path: "/"})
return sessions.Sessions("teams-session", Store)
}
// 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()
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wuzheng0709/backend-gopkg.git
git@gitee.com:wuzheng0709/backend-gopkg.git
wuzheng0709
backend-gopkg
backend-gopkg
v1.3.6

搜索帮助