1 | const github = require('octonode');
|
2 | const os = require('os');
|
3 | const prompt = require('@creuna/prompt');
|
4 |
|
5 | const messages = require('./messages');
|
6 | const configStore = require('./configstore');
|
7 |
|
8 | const storageKeys = {
|
9 | id: 'gitHubId',
|
10 | secret: 'gitHubSecret'
|
11 | };
|
12 |
|
13 | const getGitHubClient = () =>
|
14 | new Promise((resolve, reject) => {
|
15 | const secret = configStore.get(storageKeys.secret);
|
16 |
|
17 | if (secret) {
|
18 | const client = github.client(secret);
|
19 |
|
20 |
|
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 |
|
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 |
|
81 | module.exports = {
|
82 | getGitHubClient,
|
83 | storageKeys
|
84 | };
|