This commit is contained in:
aozhiwei 2024-06-03 17:20:53 +08:00
parent baad482d6d
commit 4a03b944ce
2 changed files with 1 additions and 98 deletions

View File

@ -1,7 +1,7 @@
package constant
const (
ACCOUNT_DB = "accountdb"
BCNFT_DB = "bcnftdb"
)
const (

View File

@ -1,97 +0,0 @@
package middleware
import (
"time"
"log"
"context"
"net/http"
"strings"
"github.com/gin-gonic/gin"
jwtmiddleware "github.com/auth0/go-jwt-middleware/v2"
//"github.com/auth0/go-jwt-middleware/v2/jwks"
"github.com/auth0/go-jwt-middleware/v2/validator"
)
var (
// The signing key for the token.
signingKey = []byte("secret")
// The issuer of our token.
issuer = "go-jwt-middleware-example"
// The audience of our token.
audience = []string{"audience-example"}
// Our token must be signed using this data.
keyFunc = func(ctx context.Context) (interface{}, error) {
return signingKey, nil
}
// We want this struct to be filled in with
// our custom claims from the token.
customClaims = func() validator.CustomClaims {
return &CustomClaims{}
}
)
type CustomClaims struct {
Scope string `json:"scope"`
}
func CheckJWT() gin.HandlerFunc {
// Set up the validator.
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
issuer,
audience,
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
if err != nil {
log.Fatalf("failed to set up the validator: %v", err)
}
errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("Encountered error while validating JWT: %v", err)
}
middleware := jwtmiddleware.New(
jwtValidator.ValidateToken,
jwtmiddleware.WithErrorHandler(errorHandler),
)
return func(ctx *gin.Context) {
encounteredError := true
var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
encounteredError = false
ctx.Request = r
ctx.Next()
}
middleware.CheckJWT(handler).ServeHTTP(ctx.Writer, ctx.Request)
if encounteredError {
ctx.AbortWithStatusJSON(
http.StatusUnauthorized,
map[string]string{"message": "JWT is invalid."},
)
}
}
}
func (c CustomClaims) Validate(ctx context.Context) error {
return nil
}
func (c CustomClaims) HasScope(expectedScope string) bool {
result := strings.Split(c.Scope, " ")
for i := range result {
if result[i] == expectedScope {
return true
}
}
return false
}