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