|
const http = require('http') |
|
const url = require('url') |
|
const querystring = require('querystring') |
|
const crypto = require('crypto') |
|
const opn = require('opn') |
|
|
|
const { SPOTIFY_CLIENT_ID, HOST, PORT, CALLBACK } = process.env |
|
const host = HOST || 'http://localhost' |
|
const port = PORT || 3000 |
|
const callbackPath = CALLBACK || 'callback' |
|
const spotifyAuthEndpoint = 'https://accounts.spotify.com/authorize' |
|
if (!SPOTIFY_CLIENT_ID) { |
|
console.error('Please provide a client ID.') |
|
process.exit() |
|
} |
|
|
|
const state = crypto.randomBytes(16).toString('hex') |
|
const queryParams = querystring.stringify({ |
|
response_type: 'code', |
|
client_id: SPOTIFY_CLIENT_ID, |
|
redirect_uri: `${host}:${port}/${callbackPath}`, |
|
state, |
|
}) |
|
|
|
const server = http.createServer((req, res) => { |
|
const urlParts = url.parse(req.url, true) |
|
const { query, pathname } = urlParts |
|
|
|
let message = '' |
|
if (pathname === `/${callbackPath}`) { |
|
if (query.error) { |
|
message = `Error: ${query.error}` |
|
} else if (query.state !== state) { |
|
message = 'Error: state mismatch' |
|
} else if (query.code) { |
|
message = `Access Token: ${query.code}` |
|
} else { |
|
message = 'No code returned' |
|
} |
|
console.log(message) |
|
} else { |
|
message = '404: path not found' |
|
} |
|
|
|
res.write(`<html><body><p>${message}</p></body></html>`) |
|
res.end() |
|
server.close(() => process.exit()) |
|
}) |
|
|
|
server.listen(port) |
|
const spotifyAuthURL = `${spotifyAuthEndpoint}?${queryParams}` |
|
console.log('Opening', spotifyAuthURL) |
|
opn(spotifyAuthURL) |