32 lines
848 B
Go
32 lines
848 B
Go
|
|
package auth
|
||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/subtle"
|
||
|
|
"log"
|
||
|
|
"net/http"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"git.apinb.com/ops/files/internal/config"
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
)
|
||
|
|
|
||
|
|
func ServiceAuth() gin.HandlerFunc {
|
||
|
|
return func(ctx *gin.Context) {
|
||
|
|
serviceName := strings.TrimSpace(ctx.GetHeader("Service-Name"))
|
||
|
|
secretKey := strings.TrimSpace(ctx.GetHeader("Secret-Key"))
|
||
|
|
serviceSecret, exists := config.Spec.ServiceClients[serviceName]
|
||
|
|
if serviceName == "" || secretKey == "" || !exists || strings.TrimSpace(serviceSecret) == "" || subtle.ConstantTimeCompare([]byte(serviceSecret), []byte(secretKey)) != 1 {
|
||
|
|
log.Printf("服务鉴权失败: service=%q", serviceName)
|
||
|
|
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||
|
|
ctx.Abort()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
withActor(ctx, Actor{
|
||
|
|
Type: ActorTypeService,
|
||
|
|
Identity: serviceName,
|
||
|
|
})
|
||
|
|
ctx.Next()
|
||
|
|
}
|
||
|
|
}
|