Skip to content

Commit

Permalink
feat: add unique state parameter to OAuth2 login (#292)
Browse files Browse the repository at this point in the history
  • Loading branch information
mhagmajer committed Mar 18, 2022
1 parent cca4e52 commit 5ce6a40
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 69 deletions.
91 changes: 26 additions & 65 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -39,6 +39,7 @@
"inquirer": "^6.2.0",
"js-yaml": "^3.13.1",
"lodash": "^4.17.13",
"nanoid": "^3.3.1",
"open": "^8.0.4",
"ora": "^5.4.1",
"p-event": "^2.3.1"
Expand Down
17 changes: 13 additions & 4 deletions src/commands/login.js
Expand Up @@ -14,6 +14,7 @@ const express = require('express');
const inquirer = require('inquirer');
const path = require('path');
const ora = require('ora');
const { nanoid } = require('nanoid');

class OAuthLoginCommand extends BoxCommand {
async run() {
Expand Down Expand Up @@ -65,15 +66,22 @@ class OAuthLoginCommand extends BoxCommand {

server = app.listen(port);

app.get('/callback', async(req, res) => {
const state = nanoid(32);

app.get('/callback', async (req, res) => {
try {
if (req.query.state !== state) {
throw new BoxCLIError(
`Invalid OAuth state received in callback. Got "${req.query.state}" while expecting "${state}"`
);
}
const tokenInfo = await sdk.getTokensAuthorizationCodeGrant(
req.query.code,
null
);
const tokenCache = new CLITokenCache(environmentName);
await new Promise((resolve, reject) => {
tokenCache.write(tokenInfo, error => {
tokenCache.write(tokenInfo, (error) => {
if (error) {
reject(error);
} else {
Expand Down Expand Up @@ -114,18 +122,19 @@ class OAuthLoginCommand extends BoxCommand {
spinner: 'bouncingBall',
}).start();

await new Promise(resolve => setTimeout(resolve, 1000));
await new Promise((resolve) => setTimeout(resolve, 1000));

spinner.succeed();

// the URL to redirect the user to
const authorizeUrl = sdk.getAuthorizeURL({
response_type: 'code',
state,
});

open(authorizeUrl);

await new Promise(resolve => setTimeout(resolve, 1000));
await new Promise((resolve) => setTimeout(resolve, 1000));

this.info(
chalk`{yellow If you are redirect to files view, please make sure that your Redirect URI is set up correctly and restart the login command.}`
Expand Down

0 comments on commit 5ce6a40

Please sign in to comment.