1
0
mirror of https://github.com/go-kit/kit.git synced 2025-07-15 01:04:44 +02:00

improve error handling and style

This commit is contained in:
Dmitry Salakhov
2017-09-02 21:57:51 +12:00
parent 6b4ca49912
commit 355d3e3b36
3 changed files with 16 additions and 5 deletions

View File

@ -1,4 +1,8 @@
`package auth/basic` provides a Basic Authentication middleware [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
This package provides a Basic Authentication middleware.
It'll try to compare credentials from Authentication request header to a username/password pair in middleware constructor.
More details about this type of authentication can be found in [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
## Usage
@ -6,7 +10,7 @@
import httptransport "github.com/go-kit/kit/transport/http"
httptransport.NewServer(
endpoint.Chain(AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm"))(makeUppercaseEndpoint()),
AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm")(makeUppercaseEndpoint()),
decodeMappingsRequest,
httptransport.EncodeJSONResponse,
httptransport.ServerBefore(httptransport.PopulateRequestContext),

View File

@ -34,7 +34,8 @@ func (e AuthError) Headers() http.Header {
return http.Header{
"Content-Type": []string{"text/plain; charset=utf-8"},
"X-Content-Type-Options": []string{"nosniff"},
"WWW-Authenticate": []string{fmt.Sprintf(`Basic realm=%q`, e.Realm)}}
"WWW-Authenticate": []string{fmt.Sprintf(`Basic realm=%q`, e.Realm)},
}
}
// parseBasicAuth parses an HTTP Basic Authentication string.
@ -69,7 +70,11 @@ func AuthMiddleware(requiredUser, requiredPassword, realm string) endpoint.Middl
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
auth := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string)
auth, ok := ctx.Value(httptransport.ContextKeyRequestAuthorization).(string)
if !ok {
return nil, AuthError{realm}
}
givenUser, givenPassword, ok := parseBasicAuth(auth)
if !ok {
return nil, AuthError{realm}

View File

@ -20,9 +20,11 @@ func TestWithBasicAuth(t *testing.T) {
}
tests := []struct {
name string
authHeader string
authHeader interface{}
want want
}{
{"Isn't valid with nil header", nil, want{nil, AuthError{realm}}},
{"Isn't valid with non-string header", 42, want{nil, AuthError{realm}}},
{"Isn't valid without authHeader", "", want{nil, AuthError{realm}}},
{"Isn't valid for wrong user", makeAuthString("wrong-user", requiredPassword), want{nil, AuthError{realm}}},
{"Isn't valid for wrong password", makeAuthString(requiredUser, "wrong-password"), want{nil, AuthError{realm}}},