Skip to content

Instantly share code, notes, and snippets.

@groob
Created January 13, 2017 01:58
Show Gist options
  • Save groob/ea0a3fb76ca816d5933c6bf879b42188 to your computer and use it in GitHub Desktop.
Save groob/ea0a3fb76ca816d5933c6bf879b42188 to your computer and use it in GitHub Desktop.
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