Skip to content

Commit

Permalink
get new access tokens by using new refresh tokens (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
JunNishimura committed Jul 21, 2023
1 parent 7492de0 commit 6c546b1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
8 changes: 0 additions & 8 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ import (
"github.com/google/uuid"
"github.com/pkg/browser"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
)

const (
port = "8888"
)

var (
auth *spotifyauth.Authenticator
state string
server *http.Server
)
Expand Down Expand Up @@ -50,12 +48,6 @@ func completeAuth(w http.ResponseWriter, r *http.Request) {
}

func authorize() {
auth = spotifyauth.New(
spotifyauth.WithClientID(clientViper.GetString(SpotifyIDKeyName)),
spotifyauth.WithClientSecret(clientViper.GetString(SpotifySecretKeyName)),
spotifyauth.WithRedirectURL(redirectURI),
spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate),
)
server = &http.Server{Addr: fmt.Sprintf(":%s", port)}
state = uuid.New().String()
http.HandleFunc("/callback", completeAuth)
Expand Down
26 changes: 24 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const (
)

var (
auth *spotifyauth.Authenticator
clientChannel = make(chan *spotify.Client, 1)
)

Expand All @@ -27,6 +28,13 @@ func main() {
log.Fatal(err)
}

auth = spotifyauth.New(
spotifyauth.WithClientID(clientViper.GetString(SpotifyIDKeyName)),
spotifyauth.WithClientSecret(clientViper.GetString(SpotifySecretKeyName)),
spotifyauth.WithRedirectURL(redirectURI),
spotifyauth.WithScopes(spotifyauth.ScopeUserReadPrivate),
)

// check if token viper is set
if !isClientInfoSet() {
if err := askClientInfo(); err != nil {
Expand All @@ -37,8 +45,22 @@ func main() {
} else {
ctx := context.Background()
token := getToken()
httpClient := spotifyauth.New().Client(ctx, token)
clientChannel <- spotify.New(httpClient)

newToken, err := auth.RefreshToken(ctx, token)
if err != nil {
log.Fatalf("fail to get a new access token: %v", err)
}

// update an access token if it has expired
if token.AccessToken != newToken.AccessToken {
if err := saveToken(newToken); err != nil {
log.Fatalf("fail to save token: %v", err)
}
}

spotifyClient := spotify.New(auth.Client(ctx, newToken))

clientChannel <- spotifyClient
}

client := <-clientChannel
Expand Down

0 comments on commit 6c546b1

Please sign in to comment.