lotus/lib/auth/handler.go

52 lines
997 B
Go
Raw Normal View History

package auth
import (
2019-07-23 17:27:45 +00:00
"context"
"net/http"
"strings"
logging "github.com/ipfs/go-log"
2019-12-09 17:08:32 +00:00
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/api/apistruct"
)
var log = logging.Logger("auth")
type Handler struct {
2019-10-23 09:18:22 +00:00
Verify func(ctx context.Context, token string) ([]api.Permission, error)
2019-07-23 18:49:09 +00:00
Next http.HandlerFunc
}
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
}
}
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 17:27:45 +00:00
allow, err := h.Verify(ctx, token)
if err != nil {
log.Warnf("JWT Verification failed: %s", err)
w.WriteHeader(401)
return
}
2019-12-09 17:08:32 +00:00
ctx = apistruct.WithPerm(ctx, allow)
}
h.Next(w, r.WithContext(ctx))
}