2017-04-02 22:58:39 +00:00
|
|
|
package server
|
2017-02-14 21:14:24 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/influxdata/chronograf"
|
2017-04-02 22:58:39 +00:00
|
|
|
"github.com/influxdata/chronograf/oauth2"
|
2017-02-14 21:14:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// AuthorizedToken extracts the token and validates; if valid the next handler
|
|
|
|
// will be run. The principal will be sent to the next handler via the request's
|
|
|
|
// Context. It is up to the next handler to determine if the principal has access.
|
2017-04-02 22:59:45 +00:00
|
|
|
// On failure, will return http.StatusForbidden.
|
2017-04-02 22:58:39 +00:00
|
|
|
func AuthorizedToken(auth oauth2.Authenticator, logger chronograf.Logger, next http.Handler) http.HandlerFunc {
|
2017-02-14 21:14:24 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
log := logger.
|
|
|
|
WithField("component", "auth").
|
|
|
|
WithField("remote_addr", r.RemoteAddr).
|
|
|
|
WithField("method", r.Method).
|
|
|
|
WithField("url", r.URL)
|
|
|
|
|
2017-03-30 21:59:00 +00:00
|
|
|
ctx := r.Context()
|
2017-02-14 21:14:24 +00:00
|
|
|
// We do not check the validity of the principal. Those
|
2017-02-15 22:28:17 +00:00
|
|
|
// served further down the chain should do so.
|
2017-03-31 19:48:34 +00:00
|
|
|
principal, err := auth.Validate(ctx, r)
|
2017-02-14 21:14:24 +00:00
|
|
|
if err != nil {
|
2017-03-31 19:48:34 +00:00
|
|
|
log.Error("Invalid principal")
|
|
|
|
w.WriteHeader(http.StatusForbidden)
|
2017-02-14 21:14:24 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the principal to the next handler
|
2017-04-02 22:58:39 +00:00
|
|
|
ctx = context.WithValue(ctx, oauth2.PrincipalKey, principal)
|
2017-02-14 21:14:24 +00:00
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|