This repository has been archived by the owner on Aug 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspotify.js
87 lines (80 loc) · 2.05 KB
/
spotify.js
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
const client_id = process.env.CLIENT_ID
const client_secret = process.env.CLIENT_SECRET
const redirect_uri = process.env.REDIRECT_URI
const scopes =
'playlist-read-private streaming app-remote-control user-read-playback-state user-modify-playback-state user-read-currently-playing'
const querystring = require('querystring')
const request = require('request')
class Spotify {
handleLogin(req, res) {
const url =
'https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scopes,
redirect_uri: redirect_uri,
})
res.redirect(url)
}
handleCallback(req, res) {
var code = req.query.code || null
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code',
},
headers: {
Authorization:
'Basic ' +
Buffer.from(client_id + ':' + client_secret).toString(
'base64',
),
},
json: true,
}
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token
res.redirect(
'/#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
}),
)
} else {
res.redirect(
'/#' +
querystring.stringify({
error: 'invalid_token',
}),
)
}
})
}
handleRefresh(req, res) {
var refresh_token = req.query.refresh_token;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: { 'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64')) },
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token
},
json: true
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token;
res.send({
'access_token': access_token
});
}
});
}
}
module.exports = Spotify