Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to device flow for github login #677

Merged
merged 1 commit into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 55 additions & 87 deletions src/cli/github/login.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import EventEmitter from 'events';
import chalk from 'chalk';
import Debug from 'debug';
import detectPort from 'detect-port';
import got from 'got';
import { nanoid } from 'nanoid';
import { ServerApp } from 'retes';
import { Response } from 'retes/response';
import { GET } from 'retes/route';
import type { CommandBuilder } from 'yargs';

import { Config } from '../../lib/config.js';
import { delay, openURL, printlnSuccess, successPage } from '../../lib/util.js';
import { contentBox, delay, printlnSuccess } from '../../lib/util.js';
import {
GithubLoginDeviceCodeResponse,
GithubLoginDeviceResponse,
} from '../../types.js';

const debug = Debug('saleor-cli:github:login');

Expand All @@ -20,92 +18,62 @@ export const desc = 'Add integration for Saleor CLI';
export const builder: CommandBuilder = (_) => _;

export const handler = async () => {
const port = await detectPort(3000);
const RedirectURI = `http://localhost:${port}/github/callback`;

const generatedState = nanoid();
const emitter = new EventEmitter();

const { GithubClientID, GithubClientSecret } = await Config.get();

const Params = {
client_id: GithubClientID,
redirect_uri: RedirectURI,
scope: 'repo',
};

const QueryParams = new URLSearchParams({ ...Params, state: generatedState });
const url = `https://github.com/login/oauth/authorize?${QueryParams}`;
await openURL(url);

const app = new ServerApp([
GET('/github/callback', async ({ params }) => {
const { state, code } = params;

if (state !== generatedState) {
return Response.BadRequest('Wrong state');
}

const OauthParams = {
const { GithubClientID } = await Config.get();

const {
user_code: userCode,
device_code: deviceCode,
verification_uri: verificationUri,
interval,
expires_in: expiresIn,
} = (await got
.post('https://github.com/login/device/code', {
json: {
client_id: GithubClientID,
client_secret: GithubClientSecret,
code,
redirect_uri: RedirectURI,
};

try {
const data: any = await got
.post('https://github.com/login/oauth/access_token', {
form: OauthParams,
})
.json();
scope: 'repo',
},
})
.json()) as GithubLoginDeviceResponse;

const { access_token: accessToken } = data;
contentBox(`
${chalk.bold('Please open the following URL in your browser:')}

await Config.set('github_token', `Bearer ${accessToken}`);
printlnSuccess(chalk.bold('success'));
} catch (error: any) {
console.log(error.message);
console.log(
chalk(
'Tip: in some cases',
chalk.green('saleor logout'),
'followed by',
chalk.green('saleor login'),
'may help',
),
);
${verificationUri}

emitter.emit('finish');
${chalk('And enter the following code:', chalk.bold(userCode))}`);

return {
body: successPage('Login failed!'),
status: 200,
type: 'text/html',
headers: {
'Content-Type': 'text/html; charset=utf-8',
},
};
}
const pollForAccessToken = async () => {
const { access_token: accessToken } = (await got
.post('https://github.com/login/oauth/access_token', {
json: {
client_id: GithubClientID,
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
device_code: deviceCode,
},
})
.json()) as GithubLoginDeviceCodeResponse;

if (accessToken) {
await Config.set('github_token', `Bearer ${accessToken}`);
printlnSuccess(
chalk.bold(
'You\'ve successfully authenticated GitHub with the Saleor CLI!',
),
);
process.exit(0);
}
};

emitter.emit('finish');
const expiry = Date.now() - expiresIn * 1000;

return {
body: successPage(
'You\'ve successfully authenticated Gitub with the Saleor CLI!',
),
status: 200,
type: 'text/html',
headers: {
'Content-Type': 'text/html; charset=utf-8',
},
};
}),
]);
await app.start(port);
do {
debug(Date.now());
await delay(interval * 1000);

emitter.on('finish', async () => {
await delay(1000);
await app.stop();
});
try {
await pollForAccessToken();
} catch {
return;
}
} while (Date.now() > expiry);
};
1 change: 0 additions & 1 deletion src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export type ConfigField =
| 'VercelClientSecret'
| 'SentryDSN'
| 'GithubClientID'
| 'GithubClientSecret'
| 'github_token'
| 'lastUpdateCheck';

Expand Down
14 changes: 14 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,17 @@ export interface App {
webhooks: Webhook[];
permissions: string[];
}

export type GithubLoginDeviceResponse = {
device_code: string;
user_code: string;
verification_uri: string;
expires_in: number;
interval: number;
};

export type GithubLoginDeviceCodeResponse = {
access_token: string;
token_type: string;
scope: string;
};