mirror of
https://github.com/keven1024/015.git
synced 2026-05-26 07:08:02 +00:00
feat(backend): implement custom middleware for session management and context handling
This commit is contained in:
40
backend/middleware/auth.go
Normal file
40
backend/middleware/auth.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
)
|
||||
|
||||
// CustomMiddleware 创建自定义中间件
|
||||
func AuthMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
sess, err := session.Get("session", c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sess.Options = &sessions.Options{
|
||||
Path: "/",
|
||||
MaxAge: 86400 * 7,
|
||||
HttpOnly: true,
|
||||
}
|
||||
if sess.Values["auth"] == nil {
|
||||
id, err := gonanoid.New()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sess.Values["auth"] = id
|
||||
if err := sess.Save(c.Request(), c.Response()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
cc := c.(*CustomContext)
|
||||
cc.Auth = sess.Values["auth"]
|
||||
// 将自定义上下文传递给下一个处理器
|
||||
return next(cc)
|
||||
}
|
||||
}
|
||||
}
|
||||
28
backend/middleware/context.go
Normal file
28
backend/middleware/context.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// CustomContext 扩展 echo.Context 以添加自定义功能
|
||||
type CustomContext struct {
|
||||
echo.Context
|
||||
Auth interface{}
|
||||
}
|
||||
|
||||
// NewCustomContext 创建自定义上下文的构造函数
|
||||
func NewCustomContext(c echo.Context) *CustomContext {
|
||||
return &CustomContext{
|
||||
Context: c,
|
||||
}
|
||||
}
|
||||
|
||||
// ContextMiddleware 中间件用于将标准 echo.Context 转换为 CustomContext
|
||||
func ContextMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
cc := NewCustomContext(c)
|
||||
return next(cc)
|
||||
}
|
||||
}
|
||||
}
|
||||
11
backend/middleware/session.go
Normal file
11
backend/middleware/session.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func SessionMiddleware() echo.MiddlewareFunc {
|
||||
return session.Middleware(sessions.NewCookieStore([]byte("secret")))
|
||||
}
|
||||
Reference in New Issue
Block a user