-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenManager.js
More file actions
94 lines (84 loc) · 2.4 KB
/
tokenManager.js
File metadata and controls
94 lines (84 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import crypto from 'crypto-js';
import fs from 'fs';
import path from 'path';
import url from 'url';
import inquirer from 'inquirer';
import dotenv from 'dotenv';
dotenv.config();
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
const TOKEN_PATH = path.join(__dirname, '.github_token');
const GITIGNORE_PATH = path.join(__dirname, '.gitignore');
const SECRET_KEY = process.env.SECRET_KEY;
if (!SECRET_KEY) {
console.error('No SECRET_KEY found. Please set it in your .env file.');
process.exit(1);
}
const encrypt = (text) => {
return crypto.AES.encrypt(text, SECRET_KEY).toString();
};
const decrypt = (cipherText) => {
const bytes = crypto.AES.decrypt(cipherText, SECRET_KEY);
return bytes.toString(crypto.enc.Utf8);
};
const storeToken = (token) => {
try {
fs.writeFileSync(TOKEN_PATH, encrypt(token), 'utf8');
console.log('Token stored successfully.');
ensureGitignore();
} catch (error) {
console.error('Error storing token:', error);
}
};
const ensureGitignore = () => {
try {
const gitignoreExists = fs.existsSync(GITIGNORE_PATH);
if (!gitignoreExists) {
fs.writeFileSync(GITIGNORE_PATH, '.github_token\n');
} else {
const gitignoreContent = fs.readFileSync(GITIGNORE_PATH, 'utf8');
if (!gitignoreContent.includes('.github_token')) {
fs.appendFileSync(GITIGNORE_PATH, '\n.github_token\n');
}
}
} catch (error) {
console.error('Error updating .gitignore:', error);
}
};
const retrieveToken = () => {
try {
if (!fs.existsSync(TOKEN_PATH)) return null;
const cipherText = fs.readFileSync(TOKEN_PATH, 'utf8');
return decrypt(cipherText);
} catch (error) {
console.error('Error retrieving token:', error);
return null;
}
};
const askForToken = async () => {
try {
const { token } = await inquirer.prompt([{
type: 'password',
name: 'token',
message: 'Enter your GitHub token:',
}]);
storeToken(token);
return token;
} catch (error) {
console.error('Error during token prompt:', error);
process.exit(1);
}
};
const getToken = async () => {
try {
let token = retrieveToken();
if (!token) {
console.log('GitHub token not found or expired.');
token = await askForToken();
}
return token;
} catch (error) {
console.error('Failed to handle the token retrieval process:', error);
process.exit(1);
}
};
export { getToken };