user.go 910 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package multitenant
  2. import (
  3. "fmt"
  4. "net/http"
  5. "context"
  6. "github.com/weaveworks/scope/app"
  7. )
  8. // ErrUserIDNotFound should be returned by a UserIDer when it fails to ID the
  9. // user for a request.
  10. var ErrUserIDNotFound = fmt.Errorf("User ID not found")
  11. // UserIDer identifies users given a request context.
  12. type UserIDer func(context.Context) (string, error)
  13. // UserIDHeader returns a UserIDer which a header by the supplied key.
  14. func UserIDHeader(headerName string) UserIDer {
  15. return func(ctx context.Context) (string, error) {
  16. request, ok := ctx.Value(app.RequestCtxKey).(*http.Request)
  17. if !ok || request == nil {
  18. return "", ErrUserIDNotFound
  19. }
  20. userID := request.Header.Get(headerName)
  21. if userID == "" {
  22. return "", ErrUserIDNotFound
  23. }
  24. return userID, nil
  25. }
  26. }
  27. // NoopUserIDer always returns the empty user ID.
  28. func NoopUserIDer(context.Context) (string, error) {
  29. return "", nil
  30. }