package middleware import ( "net/http" "opencatd-open/internal/auth" "opencatd-open/internal/store" "opencatd-open/internal/pkg/jwt" "github.com/gin-gonic/gin" "gorm.io/gorm" ) func Auth(db *gorm.DB) gin.HandlerFunc { return func(c *gin.Context) { authToken := c.GetHeader("Authorization") if authToken == "" { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ "code": http.StatusUnauthorized, "error": "未提供认证信息", }) return } if len(authToken) > 7 { authToken = authToken[7:] } claim, err := jwt.ValidateToken(authToken, auth.GetSecretKey()) if err != nil { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ "code": http.StatusUnauthorized, "error": "无效的认证信息", }) return } var user store.User if err := db.First(&user, claim.UserID).Error; err != nil { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ "code": http.StatusUnauthorized, "error": "无效的认证信息", }) return } c.Set("user", &user) c.Set("user_id", claim.UserID) c.Set("user_role", user.Role) c.Next() } } func CheckRole(role string) gin.HandlerFunc { return func(c *gin.Context) { c.Next() } }