2025-06-10 17:50:46 +08:00

45 lines
1.1 KiB
Go

package middleware
import (
"github.com/gin-gonic/gin"
"ifms/internal/config"
"ifms/pkg/convert"
"ifms/pkg/logging"
"ifms/pkg/util"
)
type AuthConfig struct {
AllowedPathPrefixes []string
SkippedPathPrefixes []string
RootID string
Skipper func(c *gin.Context) bool
ParseUserID func(c *gin.Context) (*config.LoginUser, error)
}
func AuthWithConfig(config AuthConfig) gin.HandlerFunc {
return func(c *gin.Context) {
if !AllowedPathPrefixes(c, config.AllowedPathPrefixes...) ||
SkippedPathPrefixes(c, config.SkippedPathPrefixes...) ||
(config.Skipper != nil && config.Skipper(c)) {
c.Next()
return
}
loginUser, err := config.ParseUserID(c)
if err != nil {
util.ResError(c, err)
return
}
loginUserId := convert.ToString(loginUser.ID)
//TODO 以后删除
ctx := util.NewUserID(c.Request.Context(), loginUserId)
ctx = util.NewLoginUser(ctx, loginUser)
ctx = logging.NewUserID(ctx, loginUserId)
if loginUserId == config.RootID {
ctx = util.NewIsRootUser(ctx)
}
c.Request = c.Request.WithContext(ctx)
c.Next()
}
}