influxdb/http/tokens.go

34 lines
806 B
Go
Raw Normal View History

2018-06-04 21:49:06 +00:00
package http
import (
"errors"
"fmt"
2018-06-04 21:49:06 +00:00
"net/http"
"strings"
)
const tokenScheme = "Token " // TODO(goller): I'd like this to be Bearer
2018-06-04 21:49:06 +00:00
// errors
var (
ErrAuthHeaderMissing = errors.New("Authorization Header is missing")
ErrAuthBadScheme = errors.New("Authorization Header Scheme is invalid")
2018-06-04 21:49:06 +00:00
)
// GetToken will parse the token from http Authorization Header.
func GetToken(r *http.Request) (string, error) {
2018-06-04 21:49:06 +00:00
header := r.Header.Get("Authorization")
if header == "" {
return "", ErrAuthHeaderMissing
}
if !strings.HasPrefix(header, tokenScheme) {
return "", ErrAuthBadScheme
}
return header[len(tokenScheme):], nil
}
// SetToken adds the token to the request.
func SetToken(token string, req *http.Request) {
req.Header.Set("Authorization", fmt.Sprintf("%s%s", tokenScheme, token))
}