2020-03-23 16:19:30 +00:00
|
|
|
package token
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/store"
|
2020-03-23 16:19:30 +00:00
|
|
|
)
|
|
|
|
|
2021-02-14 16:16:01 +03:00
|
|
|
// Options holds the options for token
|
2020-03-23 16:19:30 +00:00
|
|
|
type Options struct {
|
|
|
|
// Store to persist the tokens
|
|
|
|
Store store.Store
|
|
|
|
// PublicKey base64 encoded, used by JWT
|
|
|
|
PublicKey string
|
|
|
|
// PrivateKey base64 encoded, used by JWT
|
|
|
|
PrivateKey string
|
|
|
|
}
|
|
|
|
|
2021-02-14 16:16:01 +03:00
|
|
|
// Option func signature
|
2020-03-23 16:19:30 +00:00
|
|
|
type Option func(o *Options)
|
|
|
|
|
|
|
|
// WithStore sets the token providers store
|
|
|
|
func WithStore(s store.Store) Option {
|
|
|
|
return func(o *Options) {
|
|
|
|
o.Store = s
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithPublicKey sets the JWT public key
|
|
|
|
func WithPublicKey(key string) Option {
|
|
|
|
return func(o *Options) {
|
|
|
|
o.PublicKey = key
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithPrivateKey sets the JWT private key
|
|
|
|
func WithPrivateKey(key string) Option {
|
|
|
|
return func(o *Options) {
|
|
|
|
o.PrivateKey = key
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-14 16:16:01 +03:00
|
|
|
// NewOptions returns options struct filled by opts
|
2020-03-23 16:19:30 +00:00
|
|
|
func NewOptions(opts ...Option) Options {
|
2021-02-14 16:16:01 +03:00
|
|
|
options := Options{}
|
2020-03-23 16:19:30 +00:00
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
2021-04-27 08:32:47 +03:00
|
|
|
// set default store
|
2020-03-23 16:19:30 +00:00
|
|
|
if options.Store == nil {
|
|
|
|
options.Store = store.DefaultStore
|
|
|
|
}
|
|
|
|
return options
|
|
|
|
}
|
|
|
|
|
2021-02-14 16:16:01 +03:00
|
|
|
// GenerateOptions holds the generate options
|
2020-03-23 16:19:30 +00:00
|
|
|
type GenerateOptions struct {
|
|
|
|
// Expiry for the token
|
|
|
|
Expiry time.Duration
|
|
|
|
}
|
|
|
|
|
2021-02-14 16:16:01 +03:00
|
|
|
// GenerateOption func signature
|
2020-03-23 16:19:30 +00:00
|
|
|
type GenerateOption func(o *GenerateOptions)
|
|
|
|
|
|
|
|
// WithExpiry for the generated account's token expires
|
|
|
|
func WithExpiry(d time.Duration) GenerateOption {
|
|
|
|
return func(o *GenerateOptions) {
|
|
|
|
o.Expiry = d
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewGenerateOptions from a slice of options
|
|
|
|
func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
|
|
|
|
var options GenerateOptions
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
2021-04-27 08:32:47 +03:00
|
|
|
// set default Expiry of token
|
2020-03-23 16:19:30 +00:00
|
|
|
if options.Expiry == 0 {
|
|
|
|
options.Expiry = time.Minute * 15
|
|
|
|
}
|
|
|
|
return options
|
|
|
|
}
|