token.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package bearer
  2. import (
  3. "context"
  4. "time"
  5. )
  6. // Token provides a type wrapping a bearer token and expiration metadata.
  7. type Token struct {
  8. Value string
  9. CanExpire bool
  10. Expires time.Time
  11. }
  12. // Expired returns if the token's Expires time is before or equal to the time
  13. // provided. If CanExpires is false, Expired will always return false.
  14. func (t Token) Expired(now time.Time) bool {
  15. if !t.CanExpire {
  16. return false
  17. }
  18. now = now.Round(0)
  19. return now.Equal(t.Expires) || now.After(t.Expires)
  20. }
  21. // TokenProvider provides interface for retrieving bearer tokens.
  22. type TokenProvider interface {
  23. RetrieveBearerToken(context.Context) (Token, error)
  24. }
  25. // TokenProviderFunc provides a helper utility to wrap a function as a type
  26. // that implements the TokenProvider interface.
  27. type TokenProviderFunc func(context.Context) (Token, error)
  28. // RetrieveBearerToken calls the wrapped function, returning the Token or
  29. // error.
  30. func (fn TokenProviderFunc) RetrieveBearerToken(ctx context.Context) (Token, error) {
  31. return fn(ctx)
  32. }
  33. // StaticTokenProvider provides a utility for wrapping a static bearer token
  34. // value within an implementation of a token provider.
  35. type StaticTokenProvider struct {
  36. Token Token
  37. }
  38. // RetrieveBearerToken returns the static token specified.
  39. func (s StaticTokenProvider) RetrieveBearerToken(context.Context) (Token, error) {
  40. return s.Token, nil
  41. }