-
Notifications
You must be signed in to change notification settings - Fork 2
/
accounts.go
212 lines (181 loc) · 7.09 KB
/
accounts.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package spotify
import (
secure "crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"io"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
)
const accountsBaseURL = "https://accounts.spotify.com"
const (
// ScopeUGCImageUpload gives write access to user-provided images.
ScopeUGCImageUpload = "ugc-image-upload"
// ScopeUserReadRecentlyPlayed gives read access to a user's recently played tracks.
ScopeUserReadRecentlyPlayed = "user-read-recently-played"
// ScopeUserTopRead gives read access to a user's top artists and tracks.
ScopeUserTopRead = "user-top-read"
// ScopeUserReadPlaybackPosition gives read access to a user's playback position in a content.
ScopeUserReadPlaybackPosition = "user-read-playback-position"
// ScopeUserReadPlaybackState gives read access to a user's player state.
ScopeUserReadPlaybackState = "user-read-playback-state"
// ScopeUserModifyPlaybackState gives write access to a user's playback state.
ScopeUserModifyPlaybackState = "user-modify-playback-state"
// ScopeUserReadCurrentlyPlaying gives read access to a user's currently playing content.
ScopeUserReadCurrentlyPlaying = "user-read-currently-playing"
// ScopePlaylistModifyPublic gives write access to a user's public playlists.
ScopePlaylistModifyPublic = "playlist-modify-public"
// ScopePlaylistModifyPrivate gives write access to a user's private playlists.
ScopePlaylistModifyPrivate = "playlist-modify-private"
// ScopePlaylistReadPrivate gives read access to a user's private playlists.
ScopePlaylistReadPrivate = "playlist-read-private"
// ScopePlaylistReadCollaborative includes collaborative playlists when requesting a user's playlists.
ScopePlaylistReadCollaborative = "playlist-read-collaborative"
// ScopeUserFollowModify gives write/delete access to the list of artists and other users that the user follows.
ScopeUserFollowModify = "user-follow-modify"
// ScopeUserFollowRead gives read access to the list of artists and other users that the user follows.
ScopeUserFollowRead = "user-follow-read"
// ScopeUserLibraryModify gives write/delete access to a user's "Your Music" library.
ScopeUserLibraryModify = "user-library-modify"
// ScopeUserLibraryRead gives read access to a user's library.
ScopeUserLibraryRead = "user-library-read"
// ScopeUserReadEmail gives read access to user's email address.
ScopeUserReadEmail = "user-read-email"
// ScopeUserReadPrivate gives read access to user's subscription details (type of user account).
ScopeUserReadPrivate = "user-read-private"
)
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
}
// CreatePKCEVerifierAndChallenge generates a secure, random code verifier and code challenge for PKCE Authorization.
func CreatePKCEVerifierAndChallenge() (string, string, error) {
verifier, err := generateRandomVerifier()
if err != nil {
return "", "", err
}
challenge := calculateChallenge(verifier)
return string(verifier), challenge, nil
}
func generateRandomVerifier() ([]byte, error) {
seed, err := generateSecureSeed()
if err != nil {
return nil, err
}
rand.Seed(seed)
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-~"
verifier := make([]byte, 128)
for i := 0; i < len(verifier); i++ {
idx := rand.Intn(len(chars))
verifier[i] = chars[idx]
}
return verifier, nil
}
func generateSecureSeed() (int64, error) {
buf := make([]byte, 8)
_, err := secure.Read(buf)
if err != nil {
return 0, err
}
seed := int64(binary.BigEndian.Uint64(buf))
return seed, nil
}
func calculateChallenge(verifier []byte) string {
hash := sha256.Sum256(verifier)
challenge := base64.URLEncoding.EncodeToString(hash[:])
return strings.TrimRight(challenge, "=")
}
// GenerateRandomState creates a random hex string used to mitigate cross-site request forgery attacks.
func GenerateRandomState() (string, error) {
buf := make([]byte, 7)
_, err := rand.Read(buf)
if err != nil {
return "", err
}
state := hex.EncodeToString(buf)
return state, nil
}
// BuildAuthURI constructs the URI which users will be redirected to, to authorize the app.
func BuildAuthURI(clientID, redirectURI, state string, showDialog bool, scopes ...string) string {
q := url.Values{}
q.Add("client_id", clientID)
q.Add("response_type", "code")
q.Add("redirect_uri", redirectURI)
q.Add("code_challenge_method", "S256")
q.Add("state", state)
q.Add("scope", strings.Join(scopes, " "))
q.Add("show_dialog", strconv.FormatBool(showDialog))
return accountsBaseURL + "/authorize?" + q.Encode()
}
// BuildPKCEAuthURI constructs the URI which users will be redirected to, to authorize the app.
func BuildPKCEAuthURI(clientID, redirectURI, challenge, state string, scopes ...string) string {
q := url.Values{}
q.Add("client_id", clientID)
q.Add("response_type", "code")
q.Add("redirect_uri", redirectURI)
q.Add("code_challenge_method", "S256")
q.Add("code_challenge", challenge)
q.Add("state", state)
q.Add("scope", strings.Join(scopes, " "))
return accountsBaseURL + "/authorize?" + q.Encode()
}
// RequestToken allows a user to exchange an authorization code for an access token.
func RequestToken(clientID, code, redirectURI, clientSecret string) (*Token, error) {
query := make(url.Values)
query.Set("client_id", clientID)
query.Set("grant_type", "authorization_code")
query.Set("code", code)
query.Set("redirect_uri", redirectURI)
query.Set("client_secret", clientSecret)
body := strings.NewReader(query.Encode())
return postToken(body)
}
// RequestPKCEToken allows a user to exchange an authorization code for an access token.
func RequestPKCEToken(clientID, code, redirectURI, verifier string) (*Token, error) {
query := make(url.Values)
query.Set("client_id", clientID)
query.Set("grant_type", "authorization_code")
query.Set("code", code)
query.Set("redirect_uri", redirectURI)
query.Set("code_verifier", verifier)
body := strings.NewReader(query.Encode())
return postToken(body)
}
// RefreshToken allows a user to exchange a refresh token for an access token.
func RefreshToken(refreshToken, clientID, clientSecret string) (*Token, error) {
query := make(url.Values)
query.Set("grant_type", "refresh_token")
query.Set("refresh_token", refreshToken)
query.Set("client_id", clientID)
query.Set("client_secret", clientSecret)
body := strings.NewReader(query.Encode())
return postToken(body)
}
// RefreshPKCEToken allows a user to exchange a refresh token for an access token.
func RefreshPKCEToken(refreshToken, clientID string) (*Token, error) {
query := make(url.Values)
query.Set("grant_type", "refresh_token")
query.Set("refresh_token", refreshToken)
query.Set("client_id", clientID)
body := strings.NewReader(query.Encode())
return postToken(body)
}
func postToken(body io.Reader) (*Token, error) {
res, err := http.Post(accountsBaseURL+"/api/token", "application/x-www-form-urlencoded", body)
if err != nil {
return nil, err
}
defer res.Body.Close()
token := new(Token)
err = json.NewDecoder(res.Body).Decode(token)
return token, err
}