-
Notifications
You must be signed in to change notification settings - Fork 6
/
getIdForDomain.js
executable file
·229 lines (199 loc) · 7.01 KB
/
getIdForDomain.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/*
* Developer: Shivam Gangwar
* Maintainer: Shivam Gangwar
* Date: 19 Feb 2019
*/
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
const nodePersist = require("node-persist");
//just replace this call with our security algorithm
var crypto = require("crypto");
const path = require('path');
const TEST_BASE_DIR = path.join(__dirname, '/gdriveCred');
storage = nodePersist.create({
dir: TEST_BASE_DIR,
encoding: 'utf8',
expiredInterval: 2 * 60 * 1000, // every 2 minutes the process will clean-up the expired cache
// in some cases, you (or some other service) might add non-valid storage files to your
// storage dir, i.e. Google Drive, make this true if you'd like to ignore these files and not throw an error
forgiveParseErrors: false
});
//allow for variable storage --> security feature
storage.initSync();
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
'https://www.googleapis.com/auth/drive.appdata'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
function downloadFileFromAppDataFolder(drive, fileName){
return new Promise(function(resolve, reject){
searchFileInGdrive(drive,fileName).then(searchResult => {
if(searchResult !== 'FileNotFound'){
const dest = fs.createWriteStream(__dirname + '/gdriveCred/'+fileName);
drive.files.get({
spaces: 'appDataFolder',
fileId: searchResult,
alt: 'media'
},
{responseType: 'stream'},
function(err, res){
res.data
.on('end', () => {
dest.end();
resolve();
})
.on('error', err => {
reject(err);
})
.pipe(dest);
});
}else{
reject(searchResult);
}
});
});
}
function searchFileInGdrive(drive,fileName) {
let found = false;
return new Promise(function(resolve, reject){
drive.files.list({
spaces: 'appDataFolder',
fields: 'nextPageToken, files(id, name)',
pageSize: 100
}, function (err, res) {
if (err) {
reject(err);
console.error(err);
}
else {
let fileId = 'FileNotFound';
res.data.files.forEach(function (file) {
if(file.name === fileName){
found = true;
fileId = file.id;
resolve(fileId);
}
});
if(found === false){
resolve(fileId);
}
}
});
});
}
module.exports = {
getIdForDomain
}
function getIdForDomain(domain, masterPassword){
return new Promise((resolve,reject) => {
// Load client secrets from a local file.
fs.readFile(__dirname + '/credentials.json', (err, content) => {
if (err) reject(err);
// Authorize a client with credentials, then call the Google Drive API.
authorizeForGetDomain(JSON.parse(content), getIdsCallback, masterPassword, domain).then(accounts=>{
resolve(accounts);
}).catch(e =>{
reject(e);
});
});
});
}
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorizeForGetDomain(credentials, callback, masterPassword, domain) {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
return new Promise((resolve,reject) => {
// Check if we have previously stored a token.
fs.readFile(__dirname + '/gdriveCred/'+TOKEN_PATH, (err, token) => {
if (err){
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('[ALERT] Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('\n[INPUT] Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
new Promise(function(res, rej){
fs.writeFile(__dirname + '/gdriveCred/'+TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) rej(err);
else res();
});
}).then(function(oAuth2Client){
console.log("[SUCCESS] Token is stored at 'gdriveCred/token.json'");
//Calling main function where all the operations will be done.
callback(oAuth2Client, masterPassword, domain).then(accounts=>{
resolve(accounts);
}).catch(e =>{
reject(e.message);
});
}).catch(function(err) {
reject(err);
});
});
});
}
else{
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client, masterPassword, domain).then(accounts=>{
resolve(accounts);
}).catch(e =>{
reject(e.message);
});
}
});
});
}
/**
* Lists the names and IDs of up to 10 files.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getIdsCallback(auth,masterPassword,domain){
const drive = google.drive({ version: 'v3', auth});
return new Promise((resolve,reject) => {
downloadFileFromAppDataFolder(drive,domain).then(()=>{
let accounts = [];
let tempAccounts = getAccounts(domain, masterPassword);
for (var j = 0; j < tempAccounts.length; j++) {
accounts.push({domain:tempAccounts[j].name, id:tempAccounts[j].username,securityLevel: 1});
}
resolve(accounts);
}).catch(e =>{
reject(e);
});
}).catch(e =>{
reject(e);
});
}
function getAccounts(accountName,masterPassword){
var encryptedAccounts = storage.getItemSync(accountName);
var accounts = [];
if(typeof encryptedAccounts !== 'undefined'){
try{
let cipher = crypto.createDecipher('aes-256-cbc', masterPassword);
let decryptedAccounts = cipher.update(encryptedAccounts, 'hex', 'utf8') + cipher.final('utf8');
accounts = JSON.parse(decryptedAccounts);
}catch(exception){
throw new Error(exception.message);
}
}
return accounts;
}
module.exports = {
getIdForDomain
}