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

feat(breaking/login): remove 2fa flag in favor of better prompts #619

Merged
merged 3 commits into from
Sep 28, 2022
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
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,6 @@ For local CLI usage with a single project, you can authenticate `rdme` to your R
rdme login
```

If you have [two-factor authentication (2FA)](https://docs.readme.com/docs/two-factor-authentication) enabled on your account, you'll need to pass in the `--2fa` option:

```sh
rdme login --2fa
```

`rdme whoami` is also available to you to determine who you are logged in as, and to what project, as well as `rdme logout` for logging out of that account.

## Usage
Expand Down
7 changes: 0 additions & 7 deletions __tests__/cmds/__snapshots__/login.test.ts.snap

This file was deleted.

39 changes: 19 additions & 20 deletions __tests__/cmds/login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import getAPIMock from '../helpers/get-api-mock';

const cmd = new Command();

const apiKey = 'abcdefg';
const email = '[email protected]';
const password = '123456';
const password = 'password';
const project = 'subdomain';
const token = '123456';

describe('rdme login', () => {
beforeAll(() => nock.disableNetConnect());
Expand All @@ -33,34 +35,32 @@ describe('rdme login', () => {

it('should post to /login on the API', async () => {
prompts.inject([email, password, project]);
const apiKey = 'abcdefg';

const mock = getAPIMock().post('/api/v1/login').reply(200, { apiKey });

await expect(cmd.run({})).resolves.toMatchSnapshot();
await expect(cmd.run({})).resolves.toBe('Successfully logged in as [email protected] to the subdomain project.');

mock.done();

expect(configStore.get('apiKey')).toBe(apiKey);
expect(configStore.get('email')).toBe(email);
expect(configStore.get('project')).toBe(project);
configStore.clear();
});

it('should post to /login on the API if passing in project via opt', async () => {
prompts.inject([email, password]);
const apiKey = 'abcdefg';

const mock = getAPIMock().post('/api/v1/login').reply(200, { apiKey });

await expect(cmd.run({ project })).resolves.toMatchSnapshot();
await expect(cmd.run({ project })).resolves.toBe(
'Successfully logged in as [email protected] to the subdomain project.'
);

mock.done();

expect(configStore.get('apiKey')).toBe(apiKey);
expect(configStore.get('email')).toBe(email);
expect(configStore.get('project')).toBe(project);
configStore.clear();
});

it('should error if invalid credentials are given', async () => {
Expand All @@ -78,29 +78,28 @@ describe('rdme login', () => {
mock.done();
});

it('should error if missing two factor token', async () => {
prompts.inject([email, password, project]);
it('should make additional prompt for token if login requires 2FA', async () => {
prompts.inject([email, password, project, token]);
const errorResponse = {
error: 'LOGIN_TWOFACTOR',
message: 'You must provide a two-factor code',
suggestion: 'You can do it via the API using `token`, or via the CLI using `rdme login --2fa`',
help: 'If you need help, email [email protected] and mention log "fake-metrics-uuid".',
};

const mock = getAPIMock().post('/api/v1/login', { email, password, project }).reply(401, errorResponse);

await expect(cmd.run({})).rejects.toStrictEqual(new APIError(errorResponse));
mock.done();
});

it('should send 2fa token if provided', async () => {
const token = '123456';
prompts.inject([email, password, project, token]);
const mock = getAPIMock()
.post('/api/v1/login', { email, password, project })
.reply(401, errorResponse)
.post('/api/v1/login', { email, password, project, token })
.reply(200, { apiKey });

const mock = getAPIMock().post('/api/v1/login', { email, password, project, token }).reply(200, { apiKey: '123' });
await expect(cmd.run({})).resolves.toBe('Successfully logged in as [email protected] to the subdomain project.');

await expect(cmd.run({ '2fa': true })).resolves.toMatchSnapshot();
mock.done();

expect(configStore.get('apiKey')).toBe(apiKey);
expect(configStore.get('email')).toBe(email);
expect(configStore.get('project')).toBe(project);
});

it('should error if trying to access a project that is not yours', async () => {
Expand Down
51 changes: 29 additions & 22 deletions src/cmds/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,28 @@ import isEmail from 'validator/lib/isEmail';
import Command, { CommandCategories } from '../lib/baseCommand';
import configStore from '../lib/configstore';
import fetch, { handleRes } from '../lib/fetch';
import { debug } from '../lib/logger';
import promptTerminal from '../lib/promptWrapper';

export type Options = {
'2fa'?: boolean;
project?: string;
};

type LoginBody = {
email?: string;
password?: string;
project?: string;
token?: string;
};

function loginFetch(body: LoginBody) {
return fetch(`${config.get('host')}/api/v1/login`, {
method: 'post',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
}

export default class LoginCommand extends Command {
constructor() {
super();
Expand All @@ -34,11 +46,6 @@ export default class LoginCommand extends Command {
type: String,
description: 'Project subdomain',
},
{
name: '2fa',
type: Boolean,
description: 'Prompt for a 2FA token',
},
];
}

Expand All @@ -47,7 +54,7 @@ export default class LoginCommand extends Command {

prompts.override(opts);

const { email, password, project, token } = await promptTerminal([
const { email, password, project } = await promptTerminal([
{
type: 'text',
name: 'email',
Expand All @@ -68,11 +75,6 @@ export default class LoginCommand extends Command {
message: 'What project are you logging into?',
initial: configStore.get('project'),
},
{
type: opts['2fa'] ? 'text' : null,
name: 'token',
message: 'What is your 2FA token?',
},
]);

if (!project) {
Expand All @@ -83,17 +85,22 @@ export default class LoginCommand extends Command {
return Promise.reject(new Error('You must provide a valid email address.'));
}

return fetch(`${config.get('host')}/api/v1/login`, {
method: 'post',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
email,
password,
project,
token,
}),
})
return loginFetch({ email, password, project })
.then(handleRes)
.catch(async err => {
// if the user's login requires 2FA, let's prompt them for the token!
if (err.code === 'LOGIN_TWOFACTOR') {
debug('2FA error response, prompting for 2FA code');
const { token } = await promptTerminal({
type: 'text',
name: 'token',
message: 'What is your 2FA token?',
});

return loginFetch({ email, password, project, token }).then(handleRes);
}
throw err;
})
.then(res => {
configStore.set('apiKey', res.apiKey);
configStore.set('email', email);
Expand Down