f
This commit is contained in:
66
internal/shared/middleware/managed_ip_blacklist.go
Normal file
66
internal/shared/middleware/managed_ip_blacklist.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
securityEntities "hyapi-server/internal/domains/security/entities"
|
||||
securityServices "hyapi-server/internal/domains/security/services"
|
||||
"hyapi-server/internal/shared/interfaces"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// ManagedIPBlacklistMiddleware 管理端维护的 IP 黑名单拦截
|
||||
type ManagedIPBlacklistMiddleware struct {
|
||||
blacklist *securityServices.BlacklistService
|
||||
response interfaces.ResponseBuilder
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
func NewManagedIPBlacklistMiddleware(
|
||||
blacklist *securityServices.BlacklistService,
|
||||
response interfaces.ResponseBuilder,
|
||||
logger *zap.Logger,
|
||||
) *ManagedIPBlacklistMiddleware {
|
||||
return &ManagedIPBlacklistMiddleware{
|
||||
blacklist: blacklist,
|
||||
response: response,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ManagedIPBlacklistMiddleware) GetName() string { return "managed_ip_blacklist" }
|
||||
func (m *ManagedIPBlacklistMiddleware) GetPriority() int { return 25 }
|
||||
func (m *ManagedIPBlacklistMiddleware) IsGlobal() bool { return true }
|
||||
|
||||
func (m *ManagedIPBlacklistMiddleware) Handle() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ip := c.ClientIP()
|
||||
blocked, entry := m.blacklist.IsIPBlocked(c.Request.Context(), ip)
|
||||
if !blocked {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
reason := "IP在黑名单中"
|
||||
if entry != nil && entry.Reason != "" {
|
||||
reason = entry.Reason
|
||||
}
|
||||
m.blacklist.RecordHit(&securityEntities.BlacklistHitRecord{
|
||||
HitType: securityEntities.HitTypeIP,
|
||||
IP: ip,
|
||||
Path: c.Request.URL.Path,
|
||||
Method: c.Request.Method,
|
||||
Reason: reason,
|
||||
UserAgent: c.GetHeader("User-Agent"),
|
||||
})
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
"success": false,
|
||||
"message": "访问被拒绝",
|
||||
"error": "该IP已被列入黑名单",
|
||||
"request_id": c.GetString("request_id"),
|
||||
"timestamp": time.Now().Unix(),
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user