Reorganize project structure: - backend/cmd/openteam/ — entry point - backend/internal/ — core packages - backend/middleware/ — HTTP middleware - backend/router/ — route setup - backend/wire/ — dependency injection - backend/pkg/ — shared utilities - backend/go.mod, go.sum — Go module files Updated Makefile to work from backend/ directory. Removed old lowercase makefile.
54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
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()
|
|
}
|
|
}
|