github.com/annwntech/go-micro/v2@v2.9.5/auth/token/basic/basic.go (about) 1 package basic 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "time" 7 8 "github.com/google/uuid" 9 "github.com/annwntech/go-micro/v2/auth" 10 "github.com/annwntech/go-micro/v2/auth/token" 11 "github.com/annwntech/go-micro/v2/store" 12 ) 13 14 // Basic implementation of token provider, backed by the store 15 type Basic struct { 16 store store.Store 17 } 18 19 var ( 20 // StorePrefix to isolate tokens 21 StorePrefix = "tokens/" 22 ) 23 24 // NewTokenProvider returns an initialized basic provider 25 func NewTokenProvider(opts ...token.Option) token.Provider { 26 options := token.NewOptions(opts...) 27 28 if options.Store == nil { 29 options.Store = store.DefaultStore 30 } 31 32 return &Basic{ 33 store: options.Store, 34 } 35 } 36 37 // Generate a token for an account 38 func (b *Basic) Generate(acc *auth.Account, opts ...token.GenerateOption) (*token.Token, error) { 39 options := token.NewGenerateOptions(opts...) 40 41 // marshal the account to bytes 42 bytes, err := json.Marshal(acc) 43 if err != nil { 44 return nil, err 45 } 46 47 // write to the store 48 key := uuid.New().String() 49 err = b.store.Write(&store.Record{ 50 Key: fmt.Sprintf("%v%v", StorePrefix, key), 51 Value: bytes, 52 Expiry: options.Expiry, 53 }) 54 if err != nil { 55 return nil, err 56 } 57 58 // return the token 59 return &token.Token{ 60 Token: key, 61 Created: time.Now(), 62 Expiry: time.Now().Add(options.Expiry), 63 }, nil 64 } 65 66 // Inspect a token 67 func (b *Basic) Inspect(t string) (*auth.Account, error) { 68 // lookup the token in the store 69 recs, err := b.store.Read(StorePrefix + t) 70 if err == store.ErrNotFound { 71 return nil, token.ErrInvalidToken 72 } else if err != nil { 73 return nil, err 74 } 75 bytes := recs[0].Value 76 77 // unmarshal the bytes 78 var acc *auth.Account 79 if err := json.Unmarshal(bytes, &acc); err != nil { 80 return nil, err 81 } 82 83 return acc, nil 84 } 85 86 // String returns basic 87 func (b *Basic) String() string { 88 return "basic" 89 }