forked from damilolaolatunji/music-history
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetAccessToken.js
43 lines (35 loc) · 994 Bytes
/
getAccessToken.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
const fetch = require('node-fetch');
const spotify = require('./credentials');
const getAccessToken = (req, res, next) => {
const { code } = req.query;
if (code) {
const url = 'https://accounts.spotify.com/api/token';
const data = {
grant_type: 'authorization_code',
code,
redirect_uri: spotify.redirect_uri,
client_id: spotify.client_id,
client_secret: spotify.client_secret,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
};
const searchParams = new URLSearchParams();
Object.keys(data).forEach(prop => {
searchParams.set(prop, data[prop]);
});
fetch(url, {
method: 'POST',
headers,
body: searchParams,
})
.then(res => res.json())
.then(credentials => {
req.credentials = credentials;
req.credentials.timestamp = Date.now();
next();
})
.catch(next);
}
};
module.exports = getAccessToken;