-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (61 loc) · 2.32 KB
/
server.js
File metadata and controls
71 lines (61 loc) · 2.32 KB
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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const SpotifyWebApi = require('spotify-web-api-node');
const app = express();
app.use(express.static(__dirname + '/public'))
.use(cors())
.use(cookieParser());
const credentials = {
clientId: process.env.SPOTIPY_CLIENT_ID,
clientSecret: process.env.SPOTIPY_CLIENT_SECRET,
redirectUri: process.env.SPOTIPY_REDIRECT_URI
};
app.get('/login', (req, res) => {
const spotifyApi = new SpotifyWebApi(credentials);
const scopes = ['user-read-private', 'user-read-email', 'user-read-currently-playing', 'user-read-playback-state'];
// Create the authorization URL
const authorizeURL = spotifyApi.createAuthorizeURL(scopes, 'some-state');
res.redirect(authorizeURL);
});
app.get('/callback', (req, res) => {
const code = req.query.code || null;
const spotifyApi = new SpotifyWebApi(credentials);
spotifyApi.authorizationCodeGrant(code).then(
function (data) {
console.log('The token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
console.log('The refresh token is ' + data.body['refresh_token']);
// Redirect to the frontend with the tokens
res.redirect(`http://127.0.0.1:5173/?access_token=${data.body['access_token']}&refresh_token=${data.body['refresh_token']}`);
},
function (err) {
console.log('Something went wrong!', err);
res.redirect(`http://127.0.0.1:5173/?error=invalid_token`);
}
);
});
app.get('/refresh_token', (req, res) => {
const refresh_token = req.query.refresh_token;
const spotifyApi = new SpotifyWebApi({
...credentials,
refreshToken: refresh_token
});
spotifyApi.refreshAccessToken().then(
function (data) {
res.json({
access_token: data.body['access_token'],
expires_in: data.body['expires_in']
});
},
function (err) {
console.log('Could not refresh access token', err);
res.status(400).send('Could not refresh access token');
}
);
});
const PORT = 8888;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});