-
Notifications
You must be signed in to change notification settings - Fork 107
/
server.js
46 lines (41 loc) · 1.28 KB
/
server.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
let express = require('express')
let request = require('request')
let querystring = require('querystring')
let app = express()
let redirect_uri =
process.env.REDIRECT_URI ||
'http://localhost:8888/callback'
app.get('/login', function(req, res) {
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: process.env.SPOTIFY_CLIENT_ID,
scope: 'user-read-private user-read-email',
redirect_uri
}))
})
app.get('/callback', function(req, res) {
let code = req.query.code || null
let authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(
process.env.SPOTIFY_CLIENT_ID + ':' + process.env.SPOTIFY_CLIENT_SECRET
).toString('base64'))
},
json: true
}
request.post(authOptions, function(error, response, body) {
var access_token = body.access_token
let uri = process.env.FRONTEND_URI || 'http://localhost:3000'
res.redirect(uri + '?access_token=' + access_token)
})
})
let port = process.env.PORT || 8888
console.log(`Listening on port ${port}. Go /login to initiate authentication flow.`)
app.listen(port)