-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
196 lines (164 loc) · 5.08 KB
/
server.mjs
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import 'dotenv/config';
import express from 'express';
import next from 'next';
import axios from 'axios';
import querystring from 'query-string';
import { Buffer } from 'buffer';
import path from 'path';
import { fileURLToPath } from 'url';
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.prepare().then(() => {
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const REDIRECT_URI = process.env.REDIRECT_URI;
const PORT = process.env.PORT || 8888;
const server = express();
// Priority serve any static files
server.use(express.static(path.resolve(__dirname, './client/build')));
server.use(express.json());
/**
* Generates a random string of numbers and letters
* @param {number} length The length of the string
* @return {string} The generated string
*/
const generateRandomString = length => {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random()*possible.length));
}
return text;
};
const stateKey = 'spotify_auth_state';
server.get('/login', (req, res) => {
const staticProfile = req.query.static_profile || null;
if (staticProfile) {
res.redirect(`/?static_profile=true`);
} else {
const state = generateRandomString(16);
res.cookie(stateKey, state);
const scope = [
'user-read-private',
'user-read-email',
'user-top-read',
'playlist-modify-public',
'playlist-modify-private'
].join(' ');
const queryParams = querystring.stringify({
client_id: CLIENT_ID,
response_type: 'code',
redirect_uri: REDIRECT_URI,
state: state,
scope: scope
});
res.redirect(`https://accounts.spotify.com/authorize?${queryParams}`);
}
});
server.get('/callback', (req, res) => {
const code = req.query.code || null;
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: querystring.stringify({
grant_type: 'authorization_code',
code: code,
redirect_uri: REDIRECT_URI
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`
}
})
.then(response => {
if (response.status === 200){
const {access_token, token_type, refresh_token, expires_in} = response.data;
const queryParams = querystring.stringify({
access_token,
refresh_token,
expires_in
});
//Redirect to React app and pass along tokens in query params
res.redirect(`/?${queryParams}`);
} else {
res.redirect(`/?${querystring.stringify({
error: 'invalid_token'
})}`);
}
})
.catch(error => {
res.send(error);
});
});
server.get('/refresh_token', (req, res) => {
const { refresh_token } = req.query;
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: querystring.stringify({
grant_type: 'refresh_token',
refresh_token: refresh_token
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`
}
})
.then(response => {
res.send(response.data);
})
.catch(error => {
res.send(error);
});
});
server.post('/create_playlist', (req, res) => {
const { user_id } = req.query;
const postData = req.body;
const headers = req.headers;
axios({
method: 'post',
url: `https://api.spotify.com/v1/users/${user_id}/playlists`,
data: postData,
headers: {
'Content-Type': headers['content-type'],
Authorization: headers.authorization
}
})
.then(response => {
res.send(response.data);
})
.catch(error => {
res.send(error);
});
});
server.post('/add_tracks_playlist', (req, res) => {
const { playlist_id } = req.query;
const postData = req.body;
const headers = req.headers;
axios({
method: 'post',
url: `https://api.spotify.com/v1/playlists/${playlist_id}/tracks`,
data: postData,
headers: {
'Content-Type': headers['content-type'],
Authorization: headers.authorization
}
})
.then(response => {
res.send(response.data);
})
.catch(error => {
res.send(error);
});
});
// All other GET requests not handled before will be handled by next
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(PORT, () => {
console.log(`Express app listening at http://localhost:${PORT}`);
});
});