forked from natemoo-re/natemoo-re
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateRefreshToken.js
129 lines (111 loc) · 3.32 KB
/
generateRefreshToken.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
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
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/camelcase */
const dotenv = require("dotenv");
const fs = require("fs");
const fetch = require("node-fetch");
const querystring = require("querystring");
const http = require("http");
const open = require("open");
if (fs.existsSync(".env")) {
console.log("Using .env file to supply config environment variables");
dotenv.config({ path: ".env" });
}
if (process.env["SPOTIFY_REFRESH_TOKEN"]) {
console.log(
"Spotify Refresh Token already set, skipping Generation of Refresh Token."
);
process.exit(0);
}
const SERVER_PORT = 3000;
const requiredConfigs = ["SPOTIFY_CLIENT_ID", "SPOTIFY_CLIENT_SECRET"];
const configuration = {};
requiredConfigs.forEach((config) => {
const envVar = process.env[config];
if (!envVar) {
console.error(
`Missing config ${envVar}, set as environment variable or add to .env file.`
);
process.exit(1);
}
configuration[config] = envVar;
});
const getSpotifyToken = async (authCode) => {
const encodedCredentials = Buffer.from(
`${configuration["SPOTIFY_CLIENT_ID"]}:${configuration["SPOTIFY_CLIENT_SECRET"]}`
).toString("base64");
const getSpotifyTokenUrl = "https://accounts.spotify.com/api/token";
const body = {
grant_type: "authorization_code",
code: authCode,
redirect_uri: `http://localhost:${SERVER_PORT}/callback`,
};
const formUrlEncodedBody = querystring.stringify(body);
const getSpotifyTokenOptions = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${encodedCredentials}`,
},
body: formUrlEncodedBody,
};
const response = await fetch(getSpotifyTokenUrl, getSpotifyTokenOptions);
if (response.ok && response.body) {
const data = await response.json();
return data;
} else {
console.error(
`Error retrieving access token: ${response.status} - ${response.statusText}`
);
}
return null;
};
const writeTokenToEnvFile = (refreshToken) => {
if (fs.existsSync(".env")) {
fs.appendFile(
"./.env",
`\nSPOTIFY_REFRESH_TOKEN=${refreshToken}`,
function (err) {
if (err) throw err;
console.log("Refresh Token added to .env file");
}
);
} else {
fs.writeFile("./.env", `\nSPOTIFY_REFRESH_TOKEN=${refreshToken}`, function (
err
) {
if (err) throw err;
console.log("Refresh Token added to .env file");
});
}
};
const server = http.createServer(async function (req, res) {
if (req.url.startsWith("/callback?code=")) {
const authCode = req.url.slice("/callback?code=".length);
const tokenResponse = await getSpotifyToken(authCode);
if (tokenResponse) {
writeTokenToEnvFile(tokenResponse.refresh_token);
res.statusCode = 200;
res.write(JSON.stringify(tokenResponse, null, 4));
res.end();
} else {
res.end();
}
} else {
res.statusCode = 404;
res.end();
}
server.close();
});
server.listen(SERVER_PORT);
const SCOPES = [
"user-read-playback-state",
"user-read-currently-playing",
"user-top-read",
];
open(
`https://accounts.spotify.com/authorize?client_id=${
configuration["SPOTIFY_CLIENT_ID"]
}&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A${SERVER_PORT}%2Fcallback&scope=${SCOPES.join(
"%20"
)}`
);