2019-07-23 15:33:25 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2019-07-23 17:27:45 +00:00
|
|
|
"context"
|
2019-07-23 15:33:25 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/filecoin-project/go-lotus/api"
|
|
|
|
logging "github.com/ipfs/go-log"
|
|
|
|
)
|
|
|
|
|
|
|
|
var log = logging.Logger("auth")
|
|
|
|
|
|
|
|
type Handler struct {
|
2019-07-23 17:27:45 +00:00
|
|
|
Verify func(ctx context.Context, token string) ([]string, error)
|
2019-07-23 18:49:09 +00:00
|
|
|
Next http.HandlerFunc
|
2019-07-23 15:33:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
|
|
|
|
token := r.Header.Get("Authorization")
|
2019-07-24 21:28:51 +00:00
|
|
|
if token == "" {
|
|
|
|
token = r.FormValue("token")
|
|
|
|
if token != "" {
|
|
|
|
token = "Bearer " + token
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-23 15:33:25 +00:00
|
|
|
if token != "" {
|
|
|
|
if !strings.HasPrefix(token, "Bearer ") {
|
|
|
|
log.Warn("missing Bearer prefix in auth header")
|
|
|
|
w.WriteHeader(401)
|
|
|
|
return
|
|
|
|
}
|
2019-07-23 19:38:10 +00:00
|
|
|
token = strings.TrimPrefix(token, "Bearer ")
|
2019-07-23 15:33:25 +00:00
|
|
|
|
2019-07-23 17:27:45 +00:00
|
|
|
allow, err := h.Verify(ctx, token)
|
|
|
|
if err != nil {
|
2019-07-23 15:33:25 +00:00
|
|
|
log.Warnf("JWT Verification failed: %s", err)
|
|
|
|
w.WriteHeader(401)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-07-23 17:27:45 +00:00
|
|
|
ctx = api.WithPerm(ctx, allow)
|
2019-07-23 15:33:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
h.Next(w, r.WithContext(ctx))
|
|
|
|
}
|