cache the refreshed tokens

This commit is contained in:
2023-02-21 14:32:06 +01:00
parent b1c1d818bb
commit e0d8474c09
3 changed files with 54 additions and 48 deletions
+22 -8
View File
@@ -41,16 +41,30 @@ var spotifyPlaylistsCmd = &cobra.Command{
Take note of the desired playlist ID and add it to your config file.`,
Run: func(cmd *cobra.Command, args []string) {
var (
token = new(oauth2.Token)
auth = spotifyauth.New()
ctx = context.Background()
cachedToken = new(oauth2.Token)
auth = spotifyauth.New(
spotifyauth.WithClientID(viper.GetString("spotify_client_id")),
spotifyauth.WithClientSecret(viper.GetString("spotify_client_secret")),
spotifyauth.WithScopes(spotifyauth.ScopePlaylistModifyPublic),
)
ctx = context.Background()
)
// Spotify client initialization
token.AccessToken = viper.GetString("spotify_access_token")
token.RefreshToken = viper.GetString("spotify_refresh_token")
token.TokenType = viper.GetString("spotify_token_type")
token.Expiry = viper.GetTime("spotify_token_expiry")
client := spotify.New(auth.Client(ctx, token))
cachedToken.AccessToken = viper.GetString("spotify_access_token")
cachedToken.RefreshToken = viper.GetString("spotify_refresh_token")
cachedToken.TokenType = viper.GetString("spotify_token_type")
cachedToken.Expiry = viper.GetTime("spotify_token_expiry")
client := spotify.New(auth.Client(ctx, cachedToken))
newToken, err := client.Token()
cobra.CheckErr(err)
if newToken != cachedToken {
viper.Set("spotify_access_token", newToken.AccessToken)
viper.Set("spotify_refresh_token", newToken.RefreshToken)
viper.Set("spotify_token_type", newToken.TokenType)
viper.Set("spotify_token_expiry", newToken.Expiry)
err = viper.WriteConfig()
cobra.CheckErr(err)
}
results, err := client.CurrentUsersPlaylists(ctx, spotify.Limit(50))
if err != nil {