-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathtoken-generation.js
177 lines (139 loc) · 4.37 KB
/
token-generation.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/* eslint no-console: 0 */
import 'dotenv/config';
import ms from 'ms';
import DeepExtend from 'deep-extend';
import rc from 'rc';
import fs from 'fs-extra';
import { v4 as uuid } from 'uuid';
import { createRequire } from 'module';
import Logger from '../src/logger/logger.js';
import RepositoryModuleManager from '../src/modules/repository/repository-module-manager.js';
import jwtUtil from '../src/service/util/jwt-util.js';
const require = createRequire(import.meta.url);
const configjson = require('../config/config.json');
const pjson = require('../package.json');
const getLogger = () => new Logger('silent', false);
let repository;
const getConfig = () => {
let config;
let userConfig;
if (process.env.USER_CONFIG_PATH) {
const configurationFilename = process.env.USER_CONFIG_PATH;
const pathSplit = configurationFilename.split('/');
userConfig = JSON.parse(fs.readFileSync(configurationFilename));
userConfig.configFilename = pathSplit[pathSplit.length - 1];
}
const defaultConfig = JSON.parse(JSON.stringify(configjson[process.env.NODE_ENV]));
if (userConfig) {
config = DeepExtend(defaultConfig, userConfig);
} else {
config = rc(pjson.name, defaultConfig);
}
if (!config.configFilename) {
// set default user configuration filename
config.configFilename = '.origintrail_noderc';
}
return config;
};
const loadRepository = async () => {
repository = new RepositoryModuleManager({ logger: getLogger(), config: getConfig() });
await repository.initialize();
};
/**
* Returns argument from argv
* @param argName
* @returns {string|null}
*/
const getArg = (argName) => {
const args = process.argv;
const arg = args.find((a) => a.startsWith(argName));
if (!arg) {
return null;
}
const argSplit = arg.split('=');
if (!arg || argSplit.length < 2 || !argSplit[1]) {
return null;
}
return argSplit[1];
};
/**
* Returns user's name from arguments
* @returns {string}
*/
const getUserFromArgs = () => {
const arg = getArg('--user');
if (!arg) {
return 'node-runner';
}
return arg;
};
/**
* Returns expiresAt from arguments
* If no expiresAt is provided, null is returned
* Expressed in seconds or a string describing a time span zeit/ms
* @returns {string|null}
*/
const getExpiresInArg = () => {
const arg = getArg('--expiresIn');
if (!arg) {
return null;
}
if (!ms(arg)) {
console.log('\x1b[31m[ERROR]\x1b[0m Invalid value for expiresIn argument');
process.exit(1);
}
return arg;
};
/**
* Returns expiresAt from arguments
* If no expiresAt is provided, null is returned
* Expressed in seconds or a string describing a time span zeit/ms
* @returns {string|null}
*/
const getTokenName = () => {
const arg = getArg('--tokenName');
if (!arg) {
console.log('\x1b[31m[ERROR]\x1b[0m Missing mandatory tokenName argument.');
process.exit(1);
}
return arg;
};
const saveTokenData = async (tokenId, userId, tokenName, expiresIn) => {
let expiresAt = null;
if (expiresIn) {
const time = new Date().getTime() + ms(expiresIn);
expiresAt = new Date(time);
}
await repository.saveToken(tokenId, userId, tokenName, expiresAt);
};
const printMessage = (token, hasExpiryDate) => {
console.log('\x1b[32mAccess token successfully created.\x1b[0m ');
if (!hasExpiryDate) {
console.log('\x1b[33m[WARNING] Created token has no expiry date. \x1b[0m ');
}
console.log(token);
console.log(
'\x1b[32mMake sure to copy your personal access token now. You won’t be able to see it again!\x1b[0m ',
);
};
const getUserId = async (username) => {
const user = await repository.getUser(username);
if (!user) {
console.log(`\x1b[31m[ERROR]\x1b[0m User ${username} doesn't exist.`);
process.exit(1);
}
return user.id;
};
const generateToken = async () => {
const username = getUserFromArgs();
const expiresIn = getExpiresInArg();
const tokenName = getTokenName();
await loadRepository();
const userId = await getUserId(username);
const tokenId = uuid();
await saveTokenData(tokenId, userId, tokenName, expiresIn);
const token = jwtUtil.generateJWT(tokenId, expiresIn);
printMessage(token, expiresIn);
process.exit(0);
};
generateToken();