Spaces:
Sleeping
Sleeping
Create server.js
Browse files
server.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const express = require('express');
|
| 2 |
+
const fetch = require('node-fetch');
|
| 3 |
+
const querystring = require('querystring');
|
| 4 |
+
const app = express();
|
| 5 |
+
const port = 7860;
|
| 6 |
+
|
| 7 |
+
const clientId = process.env.SPOTIFY_CLIENT_ID;
|
| 8 |
+
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;
|
| 9 |
+
const redirectUri = process.env.SPOTIFY_REDIRECT_URI;
|
| 10 |
+
|
| 11 |
+
app.use(express.static('public'));
|
| 12 |
+
|
| 13 |
+
app.get('/login', (req, res) => {
|
| 14 |
+
const scope = 'user-read-private user-read-email';
|
| 15 |
+
res.redirect('https://accounts.spotify.com/authorize?' +
|
| 16 |
+
querystring.stringify({
|
| 17 |
+
response_type: 'code',
|
| 18 |
+
client_id: clientId,
|
| 19 |
+
scope: scope,
|
| 20 |
+
redirect_uri: redirectUri,
|
| 21 |
+
}));
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
app.get('/callback', async (req, res) => {
|
| 25 |
+
const code = req.query.code || null;
|
| 26 |
+
const authOptions = {
|
| 27 |
+
method: 'POST',
|
| 28 |
+
headers: {
|
| 29 |
+
'Authorization': 'Basic ' + (Buffer.from(clientId + ':' + clientSecret).toString('base64')),
|
| 30 |
+
'Content-Type': 'application/x-www-form-urlencoded'
|
| 31 |
+
},
|
| 32 |
+
body: querystring.stringify({
|
| 33 |
+
code: code,
|
| 34 |
+
redirect_uri: redirectUri,
|
| 35 |
+
grant_type: 'authorization_code'
|
| 36 |
+
})
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
const response = await fetch('https://accounts.spotify.com/api/token', authOptions);
|
| 40 |
+
const data = await response.json();
|
| 41 |
+
const token = data.access_token;
|
| 42 |
+
|
| 43 |
+
res.redirect('/#' + querystring.stringify({ access_token: token }));
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
app.listen(port, () => {
|
| 47 |
+
console.log(`App listening at http://localhost:${port}`);
|
| 48 |
+
});
|