40 lines
898 B
Go
40 lines
898 B
Go
package middleware
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"gin_layout/pkg/response"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func Auth(token string) gin.HandlerFunc {
|
|
expectedHash := sha256.Sum256([]byte(token))
|
|
|
|
return func(ctx *gin.Context) {
|
|
if token == "" {
|
|
response.Error(ctx, http.StatusServiceUnavailable, "authentication is not configured")
|
|
return
|
|
}
|
|
|
|
parts := strings.Fields(ctx.GetHeader("Authorization"))
|
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
|
ctx.Header("WWW-Authenticate", "Bearer")
|
|
response.Error(ctx, http.StatusUnauthorized, "unauthorized")
|
|
return
|
|
}
|
|
|
|
actualHash := sha256.Sum256([]byte(parts[1]))
|
|
if subtle.ConstantTimeCompare(actualHash[:], expectedHash[:]) != 1 {
|
|
ctx.Header("WWW-Authenticate", "Bearer")
|
|
response.Error(ctx, http.StatusUnauthorized, "unauthorized")
|
|
return
|
|
}
|
|
|
|
ctx.Next()
|
|
}
|
|
}
|