-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
84 lines (64 loc) · 2.31 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
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
const express = require('express')
const request = require('request');
const dotenv = require('dotenv');
const path = require('path');
const port = process.env.PORT || 3000;
global.access_token = ''
dotenv.config()
const spotify_client_id = process.env.SPOTIFY_CLIENT_ID
const spotify_client_secret = process.env.SPOTIFY_CLIENT_SECRET
const spotify_redirect_uri = process.env.SLUG + '/auth/callback'
var generateRandomString = function (length) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
const app = express();
app.use(express.static(path.join(__dirname, "build")));
// This route serves the React app
app.get('/', (req, res) => res.sendFile(path.resolve(__dirname, "build", "index.html")));
app.get('/auth/login', (req, res) => {
const scope = "streaming user-read-email user-read-private user-read-currently-playing user-read-playback-state user-modify-playback-state playlist-read-private"
var state = generateRandomString(16);
var auth_query_parameters = new URLSearchParams({
response_type: "code",
client_id: spotify_client_id,
scope: scope,
redirect_uri: spotify_redirect_uri,
state: state,
show_dialog: true
})
res.redirect('https://accounts.spotify.com/authorize/?' + auth_query_parameters.toString());
})
app.get('/auth/callback', (req, res) => {
var code = req.query.code;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: spotify_redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (Buffer.from(spotify_client_id + ':' + spotify_client_secret).toString('base64')),
'Content-Type' : 'application/x-www-form-urlencoded'
},
json: true
};
request.post(authOptions, function(error, response, body) {
console.log("spotify auth status code: " + response.statusCode) ;
if (!error && response.statusCode === 200) {
access_token = body.access_token;
res.redirect('/')
}
});
})
app.get('/auth/token', (req, res) => {
res.json({ access_token: access_token})
})
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
})