fleet/server/contexts/token/token.go
Zachary Wasserman 715d908613 Update go-kit to 0.4.0 (#1411)
Notable refactoring:
- Use stdlib "context" in place of "golang.org/x/net/context"
- Go-kit no longer wraps errors, so we remove the unwrap in transport_error.go
- Use MakeHandler when setting up endpoint tests (fixes test bug caught during
  this refactoring)

Closes #1411.
2017-03-15 08:55:30 -07:00

41 lines
1,013 B
Go

// Package token enables setting and reading
// authentication token contexts
package token
import (
"context"
"net/http"
"strings"
)
type key int
const tokenKey key = 0
// Token is the concrete type which represents kolide session tokens
type Token string
// FromHTTPRequest extracts an Authorization
// from an HTTP header if present.
func FromHTTPRequest(r *http.Request) Token {
headers := r.Header.Get("Authorization")
headerParts := strings.Split(headers, " ")
if len(headerParts) != 2 || strings.ToUpper(headerParts[0]) != "BEARER" {
return ""
}
return Token(headerParts[1])
}
// NewContext returns a new context carrying the Authorization Bearer token.
func NewContext(ctx context.Context, token Token) context.Context {
if token == "" {
return ctx
}
return context.WithValue(ctx, tokenKey, token)
}
// FromContext extracts the Authorization Bearer token if present.
func FromContext(ctx context.Context) (Token, bool) {
token, ok := ctx.Value(tokenKey).(Token)
return token, ok
}