-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.js
More file actions
78 lines (64 loc) · 1.75 KB
/
setup.js
File metadata and controls
78 lines (64 loc) · 1.75 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
72
73
74
75
76
77
78
'use strict';
var express = require('express');
var axios = require('axios');
const fs = require('fs');
let rawCredentialsData = fs.readFileSync('credentials.json');
let credentials = JSON.parse(rawCredentialsData);
var redirect_uri = 'http://localhost:3000/callback';
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/login', function (req, res) {
var scope = 'user-read-currently-playing user-read-playback-state';
return res.redirect(
'https://accounts.spotify.com/authorize?' +
new URLSearchParams({
response_type: 'code',
client_id: credentials.clientId,
scope: scope,
redirect_uri: redirect_uri,
}).toString(),
);
});
app.get('/callback', async (req, res) => {
var code = req.query.code || null;
const params = new URLSearchParams({
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code',
});
const axiosOptions = {
method: 'post',
url: 'https://accounts.spotify.com/api/token',
auth: {
username: credentials.clientId,
password: credentials.clientSecret,
},
data: params.toString(),
headers: { 'content-type': 'application/x-www-form-urlencoded' },
};
try {
const response = await axios(axiosOptions);
fs.writeFileSync(
'tokens.json',
JSON.stringify({
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
}),
);
return res.redirect(
'/?' +
new URLSearchParams({
success: true,
}).toString(),
);
} catch (error) {
return res.redirect(
'/#' +
new URLSearchParams({
success: false,
error: 'invalid_token',
}).toString(),
);
}
});
app.listen(3000);