UNPKG

2.85 kBJavaScriptView Raw
1"use strict";
2
3// Utils.
4const utils = require('./utils');
5
6// FS.
7const fs = require('fs');
8
9// Prompt module.
10const prompt = require('prompt');
11
12// Export object;
13const processor = {};
14
15// Sync file function.
16processor.syncFile = (program) => {
17 // Read params.
18 const passwordFile = program.args[0];
19 const realm = program.args[1];
20 const username = program.args[2];
21
22 // Encode file data.
23 const writeData = utils.encode(program);
24
25 // Collectors.
26 let found = false;
27 let newLines = [];
28
29 // Not creating file.
30 if (!program.create) {
31 // Check if file exists.
32 if (!fs.existsSync(passwordFile)) {
33 console.error(`Cannot modify file ${passwordFile}; use '-c' to create it.`);
34 return
35 }
36
37 // Read lines.
38 const lines = fs.readFileSync(passwordFile, 'UTF-8').split("\n");
39
40 // Loop lines.
41 lines.forEach(line => {
42 if (line.indexOf(`${username}:${realm}:`) === 0) {
43 found = true;
44 newLines.push(writeData);
45 console.log(`Changing password for user ${username} in realm ${realm}.`);
46 } else {
47 newLines.push(line);
48 }
49 });
50 }
51
52 // Adding user to existing file.
53 if (!found) {
54 newLines.push(writeData);
55 console.log(`Adding password for user ${username} in realm ${realm}.`);
56 }
57
58 // Write data.
59 fs.writeFileSync(passwordFile, newLines.join("\n") + "\n", 'UTF-8');
60};
61
62// Read password.
63function readPassword(program) {
64 prompt.message = "";
65 prompt.delimiter = "";
66
67 const passportOption = [{name: 'password', description: 'New password:', hidden: true}];
68 const rePassportOption = [{name: 'rePassword', description: 'Re-type new password:', hidden: true}];
69
70 // Try to read password.
71 prompt.get(passportOption, (err, result) => {
72 if (!err) {
73 const password = result.password;
74 setTimeout(function () {
75 prompt.get(rePassportOption, (err, result) => {
76 if (!err && password == result.rePassword) {
77 program.args.push(password);
78
79 try {
80 processor.syncFile(program);
81 } catch (err) {
82 console.error(err.message);
83 }
84 } else {
85 console.error("\nPassword verification error.");
86 }
87 });
88 }, 50);
89 } else {
90 console.error("\nPassword verification error.");
91 }
92 });
93}
94
95// Process command.
96processor.exec = (program) => {
97 if (program.args.length === 3) {
98 readPassword(program);
99 } else {
100 program.help();
101 }
102};
103
104// Export.
105module.exports = processor;
\No newline at end of file