forked from pocketbase/pocketbase
/
spotify.go
77 lines (66 loc) · 1.94 KB
/
spotify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package auth
import (
"context"
"encoding/json"
"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{
ctx: context.Background(),
scopes: []string{
"user-read-private",
// currently Spotify doesn't return information whether the email is verified or not
// "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.
//
// API reference: https://developer.spotify.com/documentation/web-api/reference/#/operations/get-current-users-profile
func (p *Spotify) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
data, err := p.FetchRawUserData(token)
if err != nil {
return nil, err
}
rawUser := map[string]any{}
if err := json.Unmarshal(data, &rawUser); err != nil {
return nil, err
}
extracted := struct {
Id string `json:"id"`
Name string `json:"display_name"`
Images []struct {
Url string `json:"url"`
} `json:"images"`
// don't map the email because per the official docs
// the email field is "unverified" and there is no proof
// that it actually belongs to the user
// Email string `json:"email"`
}{}
if err := json.Unmarshal(data, &extracted); err != nil {
return nil, err
}
user := &AuthUser{
Id: extracted.Id,
Name: extracted.Name,
RawUser: rawUser,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
}
if len(extracted.Images) > 0 {
user.AvatarUrl = extracted.Images[0].Url
}
return user, nil
}