Debian Codegraph @

qml/Components/PageBackup.qml

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * This file is part of the 2FA Manager App for Ubuntu Touch
3 * Copyright (C) 2019 Joan CiberSheep
4 *
5 * This App is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation.
8 *
9 *
10 * This App is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 import QtQuick 2.9
21 import Lomiri.Components 1.3
22 import Lomiri.Components.Popups 1.3
23
24 import QtQuick.LocalStorage 2.0
•25 import "../js/otpauth.js" as OTPAuth
26 import "../js/db.js" as KeysDB
27
28 Page {
29 id: backupPage
30 objectName: "backupPage"
31 anchors.fill: parent
32
33 property string path
34 //TODO: Don't hardcode it
35 property string cachePath: "/home/phablet/.cache/tfamanager.cibersheep/"
36
37 property int impSuccess
38 property int impSkipped
39 property int impError
40
41 signal isExporting()
42 signal doneExporting()
43 signal isImporting(bool isJson)
44 signal doneImporting(bool isJson)
45
46 header: HeaderSettingsSpecial {
47 id: backupHeader
48 title: i18n.tr("Manage Backups")
49 flickable: mainFlickable
50 }
51
52 ScrollView {
53 width: parent.width
54 height: parent.height
55 contentItem: mainFlickable
56 }
57
58 Flickable {
59 id: mainFlickable
60 width: parent.width
61 height: parent.height
62 contentHeight: mainColumn.height
63 topMargin: units.gu(2)
64 bottomMargin: units.gu(6)
65
66 Column {
67 id: mainColumn
68 width: parent.width
69 anchors.top: parent.top
70 anchors.topMargin: units.gu(1)
71 spacing: units.gu(4)
72
73 Label {
74 width: parent.width
75 text: i18n.tr("Export and import keys from a file")
76 font.bold: true
77 horizontalAlignment: Text.AlignHCenter
78 anchors.horizontalCenter: parent.horizontalCenter
79 wrapMode: Text.WordWrap
80 }
81
82 Column {
83 width: parent.width
84 spacing: units.gu(2)
85
86 Label {
87 width: parent.width - units.gu(4)
88 text: i18n.tr("Export all keys in one json file. Keep in mind that keys are stored as plain text.")
89 horizontalAlignment: Text.AlignJustify
90 anchors.horizontalCenter: parent.horizontalCenter
91 wrapMode: Text.WordWrap
92 }
93
94 Label {
95 width: parent.width - units.gu(4)
96 text: i18n.tr("It's advisable to encrypt that file. The <a href='https://open-store.io/app/enigma.hummlbach'>Enigma</a> app could help here.")
97 horizontalAlignment: Text.AlignJustify
98 anchors.horizontalCenter: parent.horizontalCenter
99 wrapMode: Text.WordWrap
100 onLinkActivated: Qt.openUrlExternally(link)
101 linkColor: theme.palette.normal.activity
102 }
103
104 Button {
105 id: exportButton
106 text: i18n.tr("Export json file")
107 width: Math.min(parent.width, units.gu(25))
108 anchors.horizontalCenter: parent.horizontalCenter
109
110 onClicked: requestExport();
111
112 Connections {
113 target: backupPage
114
115 onIsExporting: importButton.visible = false;
116 onDoneExporting:importButton.visible = true;
117 }
118 }
119
120 IndefinedProgressBar {
121 id: exporting
122 visible: !exportButton.visible
123 width: exportButton.width
124 height: exportButton.height
125 }
126 }
127
128
129 Column {
130 width: parent.width
131 spacing: units.gu(2)
132
133 Label {
134 width: parent.width - units.gu(4)
135 text: i18n.tr("Import keys from a json file. Select a plain text json file.")
136 horizontalAlignment: Text.AlignJustify
137 anchors.horizontalCenter: parent.horizontalCenter
138 wrapMode: Text.WordWrap
139 onLinkActivated: Qt.openUrlExternally(link)
140 }
141
142 Button {
143 id: importButton
144 text: i18n.tr("Import json file")
145 width: Math.min(parent.width, units.gu(25))
146 anchors.horizontalCenter: parent.horizontalCenter
147
148 onClicked: requestImport();
149
150 Connections {
151 target: backupPage
152
153 onIsImporting: if (isJson) importButton.visible = false;
154 onDoneImporting: {
155 console.log("Debug: Finished importing")
156 if (isJson) importButton.visible = true;
157 }
158 }
159 }
160
161 IndefinedProgressBar {
162 id: importing
163 visible: !importButton.visible
164 width: importButton.width
165 height: importButton.height
166 }
167 }
168
169 Column {
170 width: parent.width
171 spacing: units.gu(2)
172
173 Label {
174 width: parent.width - units.gu(4)
175 text: i18n.tr("Import keys from a text file containing a list of 'otpauth://' URIs. Select a plain text json file.")
176 horizontalAlignment: Text.AlignJustify
177 anchors.horizontalCenter: parent.horizontalCenter
178 wrapMode: Text.WordWrap
179 onLinkActivated: Qt.openUrlExternally(link)
180 }
181
182 Button {
183 id: importTxtButton
184 text: i18n.tr("Import text file")
185 width: Math.min(parent.width, units.gu(25))
186 anchors.horizontalCenter: parent.horizontalCenter
187
188 onClicked: requestImportTxt();
189
190 Connections {
191 target: backupPage
192
193 onIsImporting: if (!isJson) importTxtButton.visible = false;
194 onDoneImporting: if (!isJson) importTxtButton.visible = true;
195 }
196 }
197
198 IndefinedProgressBar {
199 id: importingTxt
200 visible: !importTxtButton.visible
201 width: importTxtButton.width
202 height: importTxtButton.height
203 }
204 }
205 }
206 }
207
208 Component {
209 id: importFinishedDialog
210
211 DialogImportResum {}
212 }
213
214 //TODO: Use c++ instead?
215 function saveFile(fileUrl, text, xhrAction) {
216 console.log("Requested:",xhrAction);
217 var request = new XMLHttpRequest();
218 request.open(xhrAction, fileUrl, false);
219 request.setRequestHeader("Content-Type", 'application/json');
220
221 request.onreadystatechange = function() {
222 if (xhrAction == "GET" && request.readyState == XMLHttpRequest.DONE) {
223 console.log("Json is ready");
224
225 try {
226 renderBackupJson(JSON.stringify(JSON.parse(request.responseText)));
227 } catch(e) {
228 //TODO: We might want to try if it's a text file
229 if (e instanceof SyntaxError) {
230 console.log("Syntx Error: JSON parse error");
231
232 if (request.responseText.indexOf("otpauth://") !== -1) {
233 console.log("We received a text file with URI");
234 renderUriFromTxt(request.responseText.split("\n"));
235 }
236 } else {
237 console.log("Error:",e);
238 impError += 1
239 }
240 }
241 }
242 }
243
244 request.onerror = function () {
245 error(request, request.status);
246 };
247
248 request.send(text);
249 }
250
251 function generateBackupJson(data) {
252 var jsonToReturn = {"keys": []}
253
254 if (data.length > 0) {
255 for (var i = 0; i < data.length; i++) {
256 jsonToReturn.keys.push({
257 "keyJSON": data.item(i).keyJSON,
258 "added": data.item(i).added,
259 "description": data.item(i).description
260 });
261 }
262 }
263
264 return JSON.stringify(jsonToReturn);
265 }
266
267 function renderUriFromTxt(array) {
268 var needToInitDB = false;
269
270 for (var j=0; j<array.length; j++) {
271 var termFound = null;
272
273 //Calls to the KeysDB are syncronious
274 termFound = KeysDB.findKey(array[j]);
275
276 if (termFound === true) {
277 console.log("The URI is in the db");
278 impSkipped += 1
279 } else {
280 console.log("We can add the key to the db");
281
282 KeysDB.storeKey(
283 Date(),
284 array[j],
285 ""
286 );
287
288 var needToInitDB = true;
289 impSuccess += 1
290 }
291 }
292
293 //Only initiate the DB if we did some changes to it
294 if (needToInitDB) root.initDB();
295 }
296
297 function renderBackupJson(stringFile) {
298 var needToInitDB = false;
299
300 try {
301 var currentFile = JSON.parse(stringFile);
302
303 if ("keys" in currentFile) {
304 console.log("Debug: Importing 2fa Manager json");
305
306 for (var j=0; j<currentFile.keys.length; j++) {
307 //TODO: Search for key? user and issuer?
308 var termFound = null;
309
310 //Calls to the KeysDB are syncronious
311 termFound = KeysDB.findKey(currentFile.keys[j].keyJSON);
312
313 if (termFound === true) {
314 console.log("The key is in the db");
315 impSkipped += 1;
316 } else {
317 console.log("We can add the key to the db");
318
319 KeysDB.storeKey(
320 currentFile.keys[j].added,
321 currentFile.keys[j].keyJSON,
322 currentFile.keys[j].description
323 );
324
325 var needToInitDB = true;
326 impSuccess += 1;
327 }
328 }
329 } else if ("tokens" in currentFile) {
330 //TODO: Wha about issuerAlt?
331 console.log("Debug: Importing FreeOTP+ json");
332
333 for (var j=0; j<currentFile.tokens.length; j++) {
334 if (currentFile.tokens[j].issuerExt !== currentFile.tokens[j].issuerInt) {
335 console.log("DEBUG: Attenton, issuer are different. Ext",currentFile.tokens[j].issuerExt, "Int",currentFile.tokens[j].issuerInt)
336 }
337
338 if (currentFile.tokens[j].issuerExt !== "") {
339 var currentIssuer = currentFile.tokens[j].issuerExt;
340 } else if (currentFile.tokens[j].issuerInt !== "") {
341 var issuer = currentFile.tokens[j].issuerInt;
342 }
343
344 if (currentFile.tokens[j].type == "TOTP") {
345 var otpToAdd = new OTPAuth.TOTP({
346 issuer: currentIssuer,
347 label: currentFile.tokens[j].label,
348 algorithm: currentFile.tokens[j].algo,
349 digits: currentFile.tokens[j].digits,
350 period: currentFile.tokens[j].period,
351 secret: OTPAuth.Utils.b32.fromBuf(currentFile.tokens[j].secret)
352 });
353 } else {
354 var otpToAdd = new OTPAuth.HOTP({
355 issuer: currentIssuer,
356 label: currentFile.tokens[j].label,
357 algorithm: currentFile.tokens[j].algo,
358 digits: currentFile.tokens[j].digits,
359 counter: currentFile.tokens[j].counter,
360 secret: OTPAuth.Utils.b32.fromBuf(currentFile.tokens[j].secret)
361 });
362 }
363
364 otpToAdd = OTPAuth.URI.stringify(otpToAdd);
365
366 var termFound = null;
367 termFound = KeysDB.findKey(otpToAdd);
368
369 if (termFound === true) {
370 console.log("The token is in the db");
371 impSkipped += 1;
372 } else {
373 console.log("We can add the token to the db");
374
375 KeysDB.storeKey(
376 "",
377 otpToAdd,
378 ""
379 );
380
381 var needToInitDB = true;
382 impSuccess += 1;
383 }
384 }
385 } else {
386 console.log("Error getting the 'type' of json");
387 impError += 1;
388 }
389 } catch(e) {
390 if (e instanceof SyntaxError) {
391 console.log("Syntx Error: JSON parse error");
392 } else {
393 console.log("Error:",e, currentFile);
394 }
395
396 impError += 1;
397 }
398
399 //Only initiate the DB if we did some changes to it
400 if (needToInitDB) root.initDB();
401 }
402
403 function requestExport() {
404 isExporting();
405 var date = new Date();
406 //getMoth is 0-11
407 var fileName = "export-" + date.getFullYear().toString() + String(date.getMonth() + 1) + date.getDate().toString()
408 + date.getHours().toString() + date.getMinutes().toString() + date.getSeconds().toString() + ".json";
409 var allKeys = KeysDB.getKeys();
410 var saveJson = generateBackupJson(allKeys.rows);
411 var exportJson = saveFile(cachePath + fileName, saveJson, "PUT");
412 var exportPage = mainStack.push(Qt.resolvedUrl("PageHubExport.qml"));
413 exportPage.path = cachePath + fileName;
414
415 //Delete temporary file in cache
416 exportPage.deleteCacheFile.connect(function() {
417 //Doesn't work yet
418 saveFile(cachePath + fileName, "", "DELETE");
419 });
420
421 exportPage.close.connect(function() {
422 mainStack.pop();
423 });
424
425 doneExporting();
426 }
427
428 function requestImport() {
429 //Send signal when import is started (true -> isJson)
430 isImporting(true);
431 impSuccess = 0
432 impSkipped = 0
433 impError = 0
434 var importPage = mainStack.push(Qt.resolvedUrl("PageHubImport.qml"), {"allowMultipleFiles":false});
435
436 importPage.close.connect(function() {
437 mainStack.pop();
438 doneImporting(true);
439 });
440
441 importPage.accept.connect(function(urlOfItems) {
442 for (var i=0; i<urlOfItems.length; i++) {
443 console.log("DEBUG: Url",i,"Try to parse",urlOfItems[i]);
444 saveFile(urlOfItems[i], "", "GET");
445 }
446
447 doneImporting(true);
448 showDialog();
449 });
450 }
451
452 function requestImportTxt() {
453 //Send signal when import is started (false -> !isJson)
454 isImporting(false);
455 impSuccess = 0
456 impSkipped = 0
457 impError = 0
458 var importPage = mainStack.push(Qt.resolvedUrl("PageHubImport.qml"), {"allowMultipleFiles":false});
459
460 importPage.close.connect(function() {
461 mainStack.pop();
462 doneImporting(false);
463 });
464
465 importPage.accept.connect(function(urlOfItems) {
466 for (var i=0; i<urlOfItems.length; i++) {
467 console.log("DEBUG: Import from text",i,"Try to parse",urlOfItems[i]);
468 saveFile(urlOfItems[i], "", "GET");
469 }
470
471 doneImporting(false);
472 showDialog();
473 });
474 }
475
476 function showDialog() {
477 PopupUtils.open(importFinishedDialog, backupPage, {
478 "impSuccess": impSuccess,
479 "impSkipped": impSkipped,
480 "impError": impError
481 });
482 }
483 }