token

package
v0.0.0-...-6b846f9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2021 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultTTL = 1 * time.Hour

DefaultTTL defines the default token longevity duration from the moment of its creation

View Source
const Length = 32

Length total length in bytes (including prefix, id and random bytes)

Variables

View Source
var (
	ErrNilDatabase              = errors.New("data is nil")
	ErrNilTokenStore            = errors.New("token store is nil")
	ErrEmptyTokenHash           = errors.New("token hash is empty")
	ErrTokenNotFound            = errors.New("token not found")
	ErrTokenExpired             = errors.New("token is expired")
	ErrTokenUsedUp              = errors.New("token is all used up")
	ErrTokenDuplicateCallbackID = errors.New("token callback id is already registered")
	ErrTokenCallbackNotFound    = errors.New("token callback not found")
	ErrNilTokenManager          = errors.New("token manager is nil")
	ErrNothingChanged           = errors.New("nothing changed")
	ErrDuplicateToken           = errors.New("duplicate token")
)

errors

Functions

This section is empty.

Types

type Callback

type Callback struct {
	Name     CallbackName
	Kind     Kind
	Function func(ctx context.Context, t Token) error
}

Callback is a function metadata

type CallbackError

type CallbackError struct {
	Kind  Kind
	Token Token
	Err   error
}

CallbackError represents an error which could be produced by callback

type CallbackName

type CallbackName [32]byte

func NewCallbackName

func NewCallbackName(s string) (name CallbackName)

func (CallbackName) Scan

func (name CallbackName) Scan(data interface{}) error

func (CallbackName) Value

func (name CallbackName) Value() (driver.Value, error)

type Hash

type Hash [Length]byte

Hash represents a token hash

func NewHash

func NewHash() (h Hash)

func (Hash) DecodeBinary

func (h Hash) DecodeBinary(ci *pgtype.ConnInfo, src []byte) error

func (Hash) EncodeBinary

func (h Hash) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) (newBuf []byte, err error)

func (Hash) String

func (h Hash) String() string

type Kind

type Kind uint16

ObjectKind represents the type of a token, used by a token container

const (
	TRefreshToken Kind = 1 << iota
	TSessionToken
	TEmailConfirmation
	TPhoneConfirmation

	TAll = ^Kind(0)
)

predefined token kinds

func (Kind) String

func (k Kind) String() string

type Manager

type Manager struct {
	// base context for the token callback call chain
	BaseContext context.Context

	sync.RWMutex
	// contains filtered or unexported fields
}

userManager is a general-purpose token container

func NewManager

func NewManager(s Store) (*Manager, error)

NewManager returns an initialized token container

func (*Manager) AddCallback

func (m *Manager) AddCallback(kind Kind, name CallbackName, fn func(ctx context.Context, t Token) error) error

AddCallback adds callback function to container's callstack to be called upon token checkins

func (*Manager) Checkin

func (m *Manager) Checkin(ctx context.Context, hash Hash) error

Checkin check in token for processing

func (*Manager) Cleanup

func (m *Manager) Cleanup(ctx context.Context) (err error)

Cleanup performs a full cleanup of the container by removing tokens which failed to pass validation

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, k Kind, ttl time.Duration, checkins int32) (t Token, err error)

Upsert initializes, registers and returns a new token

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, t Token) error

DeletePolicy deletes a token from the container

func (*Manager) Get

func (m *Manager) Get(ctx context.Context, hash Hash) (t Token, err error)

Get obtains a token from the container or returns ErrTokenNotFound

func (*Manager) GetCallback

func (m *Manager) GetCallback(name CallbackName) (*Callback, error)

GetCallback returns a named callback if it exists

func (*Manager) GetCallbacks

func (m *Manager) GetCallbacks(k Kind) []Callback

GetCallbacks returns callback stack by a given token kind

func (*Manager) Init

func (m *Manager) Init() error

Init initializes group manager

func (*Manager) List

func (m *Manager) List(k Kind) []Token

Registry returns a slice of tokens filtered by a given kind mask

func (*Manager) Logger

func (m *Manager) Logger() *zap.Logger

Logger returns own logger

func (*Manager) RemoveCallback

func (m *Manager) RemoveCallback(name CallbackName) error

RemoveCallback removes token callback by ObjectID, returns ErrTokenCallbackNotfound

func (*Manager) SetLogger

func (m *Manager) SetLogger(logger *zap.Logger) error

SetLogger assigns a logger to this manager

func (*Manager) Store

func (m *Manager) Store() (Store, error)

Store returns store if set

func (*Manager) Validate

func (m *Manager) Validate() error

SanitizeAndValidate validates token container

type Store

type Store interface {
	Put(ctx context.Context, t Token) error
	Get(ctx context.Context, hash Hash) (Token, error)
	Delete(ctx context.Context, hash Hash) error
}

Store describes the token store contract interface

func NewStore

func NewStore(db *pgx.Conn) (Store, error)

NewStore initializes and returns a new default token store

type Token

type Token struct {
	// the kind of operation this token is associated to
	Kind Kind `db:"kind" json:"kind"`

	// token string id
	Hash Hash `db:"hash" json:"hash"`

	// holds the initial checkin threshold number
	CheckinTotal int32 `db:"checkin_total" json:"checkin_total"`

	// holds how many checkins could be performed before it's void
	CheckinRemainder int32 `db:"checkin_remainder" json:"checkin_remainder"`

	// time when this token was created
	CreatedAt time.Time `db:"created_at" json:"created_at"`

	// denotes when this token becomes void and is removed
	ExpireAt time.Time `db:"expire_at" json:"expire_at"`
}

Hash represents a general-purpose token NOTE: the token will expire after certain conditions are met i.e. after specific time or a set number of checkins TODO add complexity variations for different use cases, i.e. SMS code should be short

func New

func New(k Kind, ttl time.Duration, checkins int32) (t Token, err error)

New creates a new token object with CSPRNG hash NOTE: payload is any token metadata that can be JSON-encoded for further processing by checkin callbacks NOTE: checkin remainder must be -1 (indefinite) or greater than 0 (default: 1)

func (Token) Validate

func (t Token) Validate() error

SanitizeAndValidate checks whether the token is expired or ran out of checkins left NOTE: returns errors instead of booleans only for more flexible explicitness

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL