UNPKG

2.46 kBJavaScriptView Raw
1const os = require('os');
2const prompt = require('@creuna/prompt');
3
4const messages = require('./messages');
5const configStore = require('./configstore');
6
7const storageKeys = {
8 id: 'gitHubId',
9 secret: 'gitHubSecret'
10};
11
12const getGitHubClient = () =>
13 new Promise((resolve, reject) => {
14 const github = require('octonode');
15 const secret = configStore.get(storageKeys.secret);
16
17 if (secret) {
18 const client = github.client(secret);
19
20 // Make request to github to verify credentials
21 client.get('', error => {
22 if (error) {
23 configStore.delete(storageKeys.id);
24 configStore.delete(storageKeys.secret);
25 reject(
26 'Failed to log in. You have been logged out. Please try logging in again.'
27 );
28 return;
29 }
30
31 resolve(client);
32 });
33
34 return;
35 }
36
37 const { shouldLogIn } = prompt({
38 shouldLogIn: {
39 text: 'Log in to GitHub?',
40 type: Boolean
41 }
42 });
43
44 if (!shouldLogIn) {
45 resolve(github.client());
46 return;
47 }
48
49 const { username, password, otp } = prompt({
50 username: 'Username',
51 password: { text: 'Password', obfuscate: true },
52 otp: '2 factor authentication code'
53 });
54
55 const tokenName = `creuna-cli_${os.hostname()}`;
56
57 github.auth.config({ username, password, otp }).login(
58 {
59 scopes: ['public_repo'],
60 note: tokenName
61 },
62 (error, id, token) => {
63 if (error) {
64 configStore.delete(storageKeys.id);
65 configStore.delete(storageKeys.secret);
66
67 messages.gitHubLoginError(tokenName);
68 reject(error);
69 return;
70 }
71
72 // According to the octonode docs, both the 'id' and the 'secret' are needed to authenticate the client in order to increase rate limits. In practice, this seemed not to work, but authenticating the client using only the 'secret' seems to work. The 'id' is kept in storage in case it's needed in the future. (it seems this response is the only time this 'id' is accessible ever, and if it turns out we need it after all, everyone would have to manually delete the 'creuna-cli' token from their accounts and log in again).
73 configStore.set(storageKeys.id, String(id));
74 configStore.set(storageKeys.secret, String(token));
75
76 return resolve(github.client(secret));
77 }
78 );
79 });
80
81module.exports = {
82 getGitHubClient,
83 storageKeys
84};