| Index: server/auth/middleware.go
|
| diff --git a/server/auth/middleware.go b/server/auth/middleware.go
|
| new file mode 100644
|
| index 0000000000000000000000000000000000000000..17473f361e4b469b44be348dc17cb593e1932273
|
| --- /dev/null
|
| +++ b/server/auth/middleware.go
|
| @@ -0,0 +1,46 @@
|
| +// Copyright 2015 The LUCI Authors. All rights reserved.
|
| +// Use of this source code is governed under the Apache License, Version 2.0
|
| +// that can be found in the LICENSE file.
|
| +
|
| +package auth
|
| +
|
| +import (
|
| + "fmt"
|
| + "net/http"
|
| +
|
| + "golang.org/x/net/context"
|
| +
|
| + "github.com/luci/luci-go/common/errors"
|
| + "github.com/luci/luci-go/common/logging"
|
| + "github.com/luci/luci-go/server/router"
|
| +)
|
| +
|
| +// Authenticate returns a middleware that performs authentication.
|
| +//
|
| +// This middleware either updates the context by injecting the authentication
|
| +// state into it (enabling functions like CurrentIdentity and IsMember), or
|
| +// aborts the request with an HTTP 401 or HTTP 500 error.
|
| +//
|
| +// Note that it passes through anonymous requests. CurrentIdentity returns
|
| +// identity.AnonymousIdentity in this case. Use separate authorization layer to
|
| +// further restrict the access, if necessary.
|
| +func Authenticate(a *Authenticator) router.Middleware {
|
| + return func(c *router.Context, next router.Handler) {
|
| + ctx, err := a.Authenticate(c.Context, c.Request)
|
| + switch {
|
| + case errors.IsTransient(err):
|
| + replyError(c.Context, c.Writer, 500, fmt.Sprintf("Transient error during authentication - %s", err))
|
| + case err != nil:
|
| + replyError(c.Context, c.Writer, 401, fmt.Sprintf("Authentication error - %s", err))
|
| + default:
|
| + c.Context = ctx
|
| + next(c)
|
| + }
|
| + }
|
| +}
|
| +
|
| +// replyError logs the error and writes it to ResponseWriter.
|
| +func replyError(c context.Context, rw http.ResponseWriter, code int, msg string) {
|
| + logging.Errorf(c, "HTTP %d: %s", code, msg)
|
| + http.Error(rw, msg, code)
|
| +}
|
|
|