[#887] added Spotify OAuth2 provider

This commit is contained in:
Olle Månsson
2022-11-01 16:06:06 +01:00
committed by GitHub
parent 9cef6ebd82
commit 639522b142
35 changed files with 121 additions and 35 deletions
+2
View File
@@ -97,6 +97,8 @@ func NewProviderByName(name string) (Provider, error) {
return NewTwitterProvider(), nil
case NameMicrosoft:
return NewMicrosoftProvider(), nil
case NameSpotify:
return NewSpotifyProvider(), nil
default:
return nil, errors.New("Missing provider " + name)
}
+9
View File
@@ -72,4 +72,13 @@ func TestNewProviderByName(t *testing.T) {
if _, ok := p.(*auth.Microsoft); !ok {
t.Error("Expected to be instance of *auth.Microsoft")
}
// spotify
p, err = auth.NewProviderByName(auth.NameSpotify)
if err != nil {
t.Errorf("Expected nil, got error %v", err)
}
if _, ok := p.(*auth.Spotify); !ok {
t.Error("Expected to be instance of *auth.Spotify")
}
}
+54
View File
@@ -0,0 +1,54 @@
package auth
import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/spotify"
)
var _ Provider = (*Spotify)(nil)
// NameSpotify is the unique name of the Spotify provider.
const NameSpotify string = "spotify"
// Spotify allows authentication via Spotify OAuth2.
type Spotify struct {
*baseProvider
}
// NewSpotifyProvider creates a new Spotify provider instance with some defaults.
func NewSpotifyProvider() *Spotify {
return &Spotify{&baseProvider{
scopes: []string{"user-read-private", "user-read-email"},
authUrl: spotify.Endpoint.AuthURL,
tokenUrl: spotify.Endpoint.TokenURL,
userApiUrl: "https://api.spotify.com/v1/me",
}}
}
// FetchAuthUser returns an AuthUser instance based on the Spotify's user api.
func (p *Spotify) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
// https://developer.spotify.com/documentation/web-api/reference/#/operations/get-current-users-profile
rawData := struct {
Id string `json:"id"`
Name string `json:"display_name"`
Email string `json:"email"`
Images []struct {
Url string `json:"url"`
} `json:"images"`
}{}
if err := p.FetchRawUserData(token, &rawData); err != nil {
return nil, err
}
user := &AuthUser{
Id: rawData.Id,
Name: rawData.Name,
Email: rawData.Email,
}
if len(rawData.Images) > 0 {
user.AvatarUrl = rawData.Images[0].Url
}
return user, nil
}