48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
const axios = require("axios");
|
|
const config = require("../config/configuration");
|
|
const fs = require("fs/promises");
|
|
const logger = require("../services/logging");
|
|
const querystring = require('node:querystring');
|
|
|
|
function authorizeSpotify(req, res) {
|
|
res.redirect("https://accounts.spotify.com/authorize?" + querystring.stringify({
|
|
response_type: "code",
|
|
client_id: config.spotify.client_id,
|
|
scope: "user-read-playback-state user-read-currently-playing",
|
|
redirect_uri: config.spotify.redirect_uri,
|
|
}));
|
|
}
|
|
|
|
async function callback(req, res) {
|
|
const code = req.query.code;
|
|
|
|
try {
|
|
const response = await axios.post("https://accounts.spotify.com/api/token",
|
|
{
|
|
code: code,
|
|
redirect_uri: config.spotify.redirect_uri,
|
|
grant_type: "authorization_code"
|
|
},
|
|
{
|
|
headers: {
|
|
"Authorization": "Basic " + new Buffer.from(config.spotify.client_id + ':' + config.spotify.client_secret).toString('base64'),
|
|
"Content-Type": "application/x-www-form-urlencoded"
|
|
}
|
|
}
|
|
);
|
|
|
|
const data = response.data;
|
|
data["expires_at"] = Date.now() + data["expires_in"] * 1000;
|
|
await fs.writeFile("credentials.spotify.json", JSON.stringify(data));
|
|
|
|
res.redirect("/");
|
|
} catch (ex) {
|
|
logger.error(ex, "Failed to get Spotify oauth.");
|
|
res.send({ 'error': "Something went wrong with spotify's oauth flow" });
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
authorizeSpotify,
|
|
callback
|
|
} |