init
This commit is contained in:
commit
aee8bcc886
18 files changed
+960
No files matched your search
@@ -0,0 +1,39 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user