Created
May 8, 2018 21:28
-
-
Save sheminusminus/d98dc326658665ff061e46be69a83e43 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const router = express.Router(); | |
router.post('/swap', async (req, res) => { | |
const { code } = req.body; | |
try { | |
const url = `${spotifyConfig.SPOTIFY_ENDPOINT}/api/token`; | |
const postOptions = { | |
method: 'POST', | |
url, | |
headers: { | |
Authorization: spotifyConfig.AUTH_HEADER, | |
}, | |
params: { | |
grant_type: 'authorization_code', | |
redirect_uri: spotifyConfig.CALLBACK_URL, | |
code, | |
}, | |
json: true, | |
}; | |
const response = await axios(postOptions); | |
const { data } = response; | |
const tokenData = Object.assign({}, data); | |
const refreshToken = tokenData.refresh_token; | |
if (refreshToken) { | |
const encryptedToken = Crypto.symmetricEncrypt(refreshToken, spotifyConfig.ENCRYPTION_SECRET); | |
tokenData.refresh_token = encryptedToken; | |
res.status(200).send(tokenData); | |
} | |
} catch (err) { | |
console.log(err); | |
res.status(400).send({ message: 'error' }); | |
} | |
}); | |
router.post('/refresh', async (req, res) => { | |
const { refresh_token } = req.body; | |
const decryptedToken = Crypto.symmetricDecrypt(refresh_token, spotifyConfig.ENCRYPTION_SECRET); | |
try { | |
const url = `${spotifyConfig.SPOTIFY_ENDPOINT}/api/token`; | |
const postOptions = { | |
method: 'POST', | |
url, | |
headers: { | |
Authorization: spotifyConfig.AUTH_HEADER, | |
}, | |
params: { | |
grant_type: 'refresh_token', | |
refresh_token: decryptedToken, | |
}, | |
json: true, | |
}; | |
const response = await axios(postOptions); | |
const { data } = response; | |
res.status(200).send(data); | |
} catch (err) { | |
console.log(err); | |
res.status(400).send({ message: 'error' }); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment