-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (83 loc) · 2.48 KB
/
index.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
88
89
var secrets = require('./secrets.json')
var express = require('express');
var cors = require('cors')
var querystring = require('querystring');
var request = require('request')
const fs = require('fs')
var app = express();
app.use(express.static(__dirname + '/public'))
.use(cors())
app.set('view engine', 'ejs');
var client_id = secrets.client_id
var client_secret = secrets.client_secret
var redirect_uri = 'http://localhost:3000/callback'
app.get('/login', function(req, res){
// res.send('login')
// res.redirect('http://globo.com')
var scopes = 'user-read-private user-read-email user-top-read';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scopes,
redirect_uri: redirect_uri
})
)
})
app.get('/callback', function(req, res){
var code = req.query.code || null;
var state = req.query.state || null;
var error = req.query.error || null;
if (!error && code) {
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(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
console.log(body)
var options = {
url: 'https://api.spotify.com/v1/me/top/artists',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
}
request.get(options, function(error, response, body) {
var json = JSON.stringify(body.items);
fs.writeFile('results.json', json, function(err){
if(err){
return console.log('ERRO')
}
})
});
res.redirect('/?' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
})
)
}
})
}
})
app.get('/', function(req, res){
var artists = []
fs.readFile('results.json', function(err, data){
artists = JSON.parse(data)
res.render('pages/index', {
artists: artists
})
})
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});