Skip to content

Instantly share code, notes, and snippets.

@t-davies
Last active November 18, 2020 10:34
Show Gist options
  • Save t-davies/2e40373219b43090b5909e0cad73fbb1 to your computer and use it in GitHub Desktop.
Save t-davies/2e40373219b43090b5909e0cad73fbb1 to your computer and use it in GitHub Desktop.
Slightly messy reference for implementing client-side OAuth 2 flow in a CLI app
// quick and dirty reference for oauth flow in CLI apps
let server: http.Server;
const recievedCode = new Promise<string>((resolve, reject) => {
server = http.createServer((req, res) => {
const { pathname, searchParams } = new URL(
req.url,
"http://localhost:3000/"
);
if (pathname.includes("oauth")) {
console.log({
message: "got oauth callback",
parameters: searchParams.toString(),
});
if (searchParams.has("code")) {
resolve(searchParams.get("code"));
} else {
reject("bad oauth response");
}
res.writeHead(200, "OK");
res.end();
} else {
res.writeHead(200, "OK");
res.write(`signed in`);
res.end();
}
});
server.listen(3000);
});
open(
`https://id.twitch.tv/oauth2/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(
"http://localhost:3000/oauth"
)}&response_type=code&scope=${encodeURIComponent(
["channel:manage:broadcast", "analytics:read:extensions"].join(" ")
)}&login_hint=${username}&hint=${username}`
);
const code = await recievedCode;
server.close();
console.log({
message: "exchanging access code for token",
code,
});
const response = await fetch(
`https://id.twitch.tv/oauth2/token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}&grant_type=authorization_code&redirect_uri=${encodeURIComponent(
"http://localhost:3000/"
)}`,
{
method: "POST",
}
);
if (response.ok) {
try {
const body = await response.json();
console.log({ message: "successfully got access token" });
return body.access_token;
} catch (err) {
console.log({
message: "failed to parse sign in response",
error: err,
});
}
} else {
try {
console.log({
message: "bad request to token endpoint",
body: await response.json(),
});
} catch {}
}
@t-davies
Copy link
Author

npm install open

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment