Last active
July 28, 2021 13:54
-
-
Save renskiy/668771464b2b71af7304e4c429ca44fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "time" | |
| "github.com/kevinburke/twilio-go/token" | |
| "github.com/pkg/errors" | |
| ) | |
| type invalidGrant string // this type can not be used as grant container | |
| type properGrant map[string]interface{} // this type is expected to be a proper container for the grant | |
| func newPlayerGrant(rawGrant string) (*playerGrant, error) { | |
| grant := make(properGrant) | |
| if err := json.Unmarshal([]byte(rawGrant), &grant); err != nil { | |
| return nil, errors.Wrap(err, "can't decode playerGrant") | |
| } | |
| return &playerGrant{grant: grant}, nil | |
| } | |
| type playerGrant struct { | |
| grant properGrant | |
| } | |
| func (g *playerGrant) ToPayload() map[string]interface{} { | |
| return g.grant | |
| } | |
| func (g *playerGrant) Key() string { | |
| return "player" | |
| } | |
| func main() { | |
| grant, err := newPlayerGrant(fetchGrantFromTwilioAPI()) | |
| if err != nil { | |
| panic(err) | |
| } | |
| playerAccessToken := token.New("AccountSid", "APIKey", "APISecret", "identity", time.Minute) | |
| playerAccessToken.AddGrant(grant) // if grant can't be decoded to map[string]interface{} then this will not work | |
| jwt, err := playerAccessToken.JWT() | |
| if err != nil { | |
| panic(err) | |
| } | |
| fmt.Printf("generated token is %q", jwt) | |
| } | |
| func fetchGrantFromTwilioAPI() string { | |
| // grant has to be of `object` type | |
| return `{"grant": "<grant_content>"}` // try to replace this string with something that isn't JSON object and you will get an error | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment