harbor/utils/registry/auth/authorizer.go

75 lines
2.0 KiB
Go
Raw Normal View History

2016-04-27 11:59:43 +02:00
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package auth
import (
"fmt"
2016-04-27 11:59:43 +02:00
"net/http"
au "github.com/docker/distribution/registry/client/auth"
"github.com/vmware/harbor/utils/registry/utils"
2016-04-27 11:59:43 +02:00
)
// Authorizer authorizes requests according to the schema
type Authorizer interface {
2016-04-28 12:49:59 +02:00
// Scheme : basic, bearer
Scheme() string
//Authorize adds basic auth or token auth to the header of request
Authorize(req *http.Request, params map[string]string) error
2016-04-27 11:59:43 +02:00
}
// AuthorizerStore holds a authorizer list, which will authorize request.
// And it implements interface Modifier
type AuthorizerStore struct {
authorizers []Authorizer
challenges []au.Challenge
2016-04-27 11:59:43 +02:00
}
// NewAuthorizerStore ...
func NewAuthorizerStore(endpoint string, authorizers ...Authorizer) (*AuthorizerStore, error) {
endpoint = utils.FormatEndpoint(endpoint)
resp, err := http.Get(buildPingURL(endpoint))
if err != nil {
return nil, err
2016-04-27 11:59:43 +02:00
}
challenges := ParseChallengeFromResponse(resp)
return &AuthorizerStore{
authorizers: authorizers,
challenges: challenges,
}, nil
}
func buildPingURL(endpoint string) string {
return fmt.Sprintf("%s/v2/", endpoint)
2016-04-27 11:59:43 +02:00
}
// Modify adds authorization to the request
func (a *AuthorizerStore) Modify(req *http.Request) error {
for _, challenge := range a.challenges {
for _, authorizer := range a.authorizers {
if authorizer.Scheme() == challenge.Scheme {
if err := authorizer.Authorize(req, challenge.Parameters); err != nil {
2016-04-27 11:59:43 +02:00
return err
}
}
}
}
return nil
}