code.dwrz.net

Go monorepo.
Log | Files | Refs

token.go (1377B)


      1 package bearer
      2 
      3 import (
      4 	"context"
      5 	"time"
      6 )
      7 
      8 // Token provides a type wrapping a bearer token and expiration metadata.
      9 type 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.
     18 func (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.
     27 type 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.
     33 type TokenProviderFunc func(context.Context) (Token, error)
     34 
     35 // RetrieveBearerToken calls the wrapped function, returning the Token or
     36 // error.
     37 func (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.
     43 type StaticTokenProvider struct {
     44 	Token Token
     45 }
     46 
     47 // RetrieveBearerToken returns the static token specified.
     48 func (s StaticTokenProvider) RetrieveBearerToken(context.Context) (Token, error) {
     49 	return s.Token, nil
     50 }