Last active
December 26, 2019 12:13
-
-
Save agtorre/350c5b4ce0ccebc5ac0f to your computer and use it in GitHub Desktop.
Store OAuth2 Token Using Redis
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
type Config struct { | |
*oauth2.Config | |
Redis MyRedisInterface | |
} | |
func (c *Config) StoreToken(token *oauth2.Token) error { | |
//store the token in redis here using c.Redis | |
} | |
func (c *Config) Exchange(ctx context.Context, code string) (*oauth2.Token, error) { | |
token, err := c.Config.Exchange(ctx, code) | |
if err != nil { | |
return nil, err | |
} | |
if err := c.StoreToken(token); err != nil { | |
return nil, err | |
} | |
return token, nil | |
} | |
func (c *Config) Client(ctx context.Context, t *Token) *http.Client { | |
return oauth2.NewClient(ctx, c.TokenSource(ctx, t)) | |
} | |
func (c *Config) TokenSource(ctx context.Context, t *oauth2.Token) oauth2.TokenSource { | |
rts := &RedisTokenSource{ | |
source: c.Config.TokenSource(ctx, t), | |
config: c, | |
} | |
return oauth2.ReuseTokenSource(t, rts) | |
} | |
type RedisTokenSource struct { | |
source oauth2.TokenSource | |
config *Config | |
} | |
func (t *RedisTokenSource) Token() (*oauth2.Token, error) { | |
token, err := t.source.Token() | |
if err != nil{ | |
return nil, err | |
} | |
if err := t.config.StoreToken(token); err != nil { | |
return nil, err | |
} | |
return token, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: