Created
January 13, 2017 01:58
-
-
Save groob/ea0a3fb76ca816d5933c6bf879b42188 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package scoped | |
import ( | |
"errors" | |
"github.com/go-kit/kit/auth/jwt" | |
"github.com/go-kit/kit/endpoint" | |
"golang.org/x/net/context" | |
) | |
var errNoClaims = errors.New("context missing claims") | |
var errNoScopes = errors.New("claim missing scopes key") | |
var errNotAllowed = errors.New("not allowed") | |
func EndpointMiddleware(allowed []string) endpoint.Middleware { | |
return func(next endpoint.Endpoint) endpoint.Endpoint { | |
return func(ctx context.Context, request interface{}) (response interface{}, err error) { | |
claims, ok := ctx.Value(jwt.JWTClaimsContextKey).(jwt.Claims) | |
if !ok { | |
return nil, errNoClaims | |
} | |
scopes, ok := claims["scopes"].([]string) | |
if !ok { | |
return nil, errNoScopes | |
} | |
if !verifyScopes(scopes, allowed) { | |
return nil, errNotAllowed | |
} | |
return next(ctx, request) | |
} | |
} | |
} | |
func verifyScopes(have, allowed []string) bool { | |
for _, allow := range allowed { | |
for _, scope := range have { | |
if scope == allow { | |
return true | |
} | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment