aboutsummaryrefslogtreecommitdiffhomepage
path: root/public
diff options
context:
space:
mode:
authorMarvin Borner2019-01-26 18:28:13 +0100
committerMarvin Borner2019-01-26 18:28:13 +0100
commit95c39ac875b7dda792057884d0901b9caad7c740 (patch)
tree197b618cf0a66a005790364ad206d56477c3d2fb /public
parente8c9f6873a2291958bad19329fb9b4a037f52c21 (diff)
Reworked database and async methods
Diffstat (limited to 'public')
-rw-r--r--public/scripts/2_encryption.js78
-rw-r--r--public/scripts/chat.js4
2 files changed, 35 insertions, 47 deletions
diff --git a/public/scripts/2_encryption.js b/public/scripts/2_encryption.js
index 17bce3d..fbc46fe 100644
--- a/public/scripts/2_encryption.js
+++ b/public/scripts/2_encryption.js
@@ -1,45 +1,31 @@
-const sql = require('alasql');
+const Dexie = require('dexie');
const openpgp = require('openpgp');
openpgp.initWorker({path: 'openpgp.worker.js'});
+let db;
+
/**
* Generates database and tables
* @returns Boolean
*/
function setupDatabase() {
- return sql('CREATE INDEXEDDB DATABASE IF NOT EXISTS texx; \
- ATTACH INDEXEDDB DATABASE texx; \
- USE texx; \
- CREATE TABLE IF NOT EXISTS own_keys (key_type STRING, key_data STRING); \
- CREATE TABLE IF NOT EXISTS peer_keys (peer_id STRING, key_data STRING); \
- CREATE TABLE IF NOT EXISTS messages (id INT AUTO_INCREMENT, message STRING);', () => {
- localStorage.setItem('database', 'success');
- return true;
- })
-}
+ db = new Dexie('texx');
+ window.db = db;
+ db.version(2).stores({
+ own_keys: '&key_type, key_data',
+ peer_keys: 'peer_id, key_data',
+ messages: 'peer_id, message'
+ });
-/**
- * Sets up connection between memory storage and indexeddb
- */
-function setupDatabaseConnection() {
- sql.promise('CREATE INDEXEDDB DATABASE IF NOT EXISTS texx; ATTACH INDEXEDDB DATABASE texx; USE texx;')
-}
+ localStorage.setItem('database', 'success');
-window.test = (() => {
- sql('CREATE INDEXEDDB DATABASE IF NOT EXISTS geo;\
- ATTACH INDEXEDDB DATABASE geo; \
- USE geo; \
- CREATE TABLE IF NOT EXISTS cities (city string, population number); \
- INSERT INTO cities Values ("' + (Math.random() * 100) + '","' + (Math.random() * 100) + '")', function () {
-
- // Select data from IndexedDB
- sql.promise('SELECT * FROM cities')
- .then(function (res) {
- console.log(res);
- });
+ db.open().catch(e => {
+ localStorage.setItem('database', 'failed');
+ console.error("Database failed: " + e.stack);
});
-});
+ return true;
+}
/**
* Generates and stores encrypted private key, public key and a revocation certificate
@@ -55,9 +41,9 @@ async function generateKeys(peerId, passphrase) {
};
await openpgp.generateKey(options).then(async (key) => {
- await sql.promise([`INSERT INTO own_keys VALUES ("private_key", "${key.privateKeyArmored}");`,
- `INSERT INTO own_keys VALUES ("public_key", "${key.publicKeyArmored}");`,
- `INSERT INTO own_keys VALUES ("revocation_certificate", "${key.revocationCertificate}");`]).then(() =>
+ await db.own_keys.put({key_type: 'private_key', key_data: key.privateKeyArmored});
+ await db.own_keys.put({key_type: 'public_key', key_data: key.publicKeyArmored});
+ await db.own_keys.put({key_type: 'revocation_certificate', key_data: key.revocationCertificate}).then(() =>
console.log('[LOG] Successfully generated and stored keys!')
);
});
@@ -68,7 +54,7 @@ async function generateKeys(peerId, passphrase) {
* @returns {Promise<String>}
*/
async function getPrivateKey() {
- return await sql.promise('SELECT key_data FROM own_keys WHERE key_type = "private_key" LIMIT 1').then(res => res.length > 0 ? res[0]['key_data'] : '');
+ return await db.own_keys.where('key_type').equals('private_key').limit(1).toArray().then(res => res.length > 0 ? res[0]['key_data'] : '');
}
/**
@@ -76,7 +62,7 @@ async function getPrivateKey() {
* @returns {Promise<String>}
*/
async function getPublicKey() {
- return await sql.promise('SELECT key_data FROM own_keys WHERE key_type = "public_key" LIMIT 1').then(res => res.length > 0 ? res[0]['key_data'] : '');
+ return await db.own_keys.where('key_type').equals('public_key').limit(1).toArray().then(res => res.length > 0 ? res[0]['key_data'] : '');
}
/**
@@ -84,7 +70,7 @@ async function getPublicKey() {
* @returns {Promise<String>}
*/
async function getRevocationCertificate() {
- return await sql.promise('SELECT key_data FROM own_keys WHERE key_type = "revocation_certificate" LIMIT 1').then(res => res.length > 0 ? res[0]['key_data'] : '');
+ return await db.own_keys.where('key_type').equals('public_key').limit(1).toArray().then(res => res.length > 0 ? res[0]['key_data'] : '');
}
/**
@@ -137,10 +123,15 @@ async function decrypt(data, publicKey, privateKey, passphrase) {
* @returns {boolean}
*/
async function isEncrypted() {
- const hasPrivateKey = await getPrivateKey().then(res => res !== '');
- const hasPublicKey = await getPublicKey().then(res => res !== '');
- const hasRevocationCertificate = await getRevocationCertificate().then(res => res !== '');
- return (hasPrivateKey && hasPublicKey && hasRevocationCertificate);
+ return await Dexie.exists('texx').then(async (exists) => {
+ if (exists) {
+ const hasPrivateKey = await getPrivateKey().then(res => res !== '');
+ const hasPublicKey = await getPublicKey().then(res => res !== '');
+ const hasRevocationCertificate = await getRevocationCertificate().then(res => res !== '');
+ return (hasPrivateKey && hasPublicKey && hasRevocationCertificate);
+ } else
+ return false;
+ });
}
/**
@@ -151,7 +142,7 @@ async function isEncrypted() {
async function storePeerPublicKey(peerId, key) {
console.log(peerId);
console.log(key);
- await sql.promise(`INSERT INTO peer_keys VALUES ("${peerId}", "${key}")`).then(() =>
+ await db.peer_keys.put({peer_id: peerId, key_data: key}).then(() =>
console.log('[LOG] Stored public key of ' + peerId)
);
}
@@ -162,7 +153,7 @@ async function storePeerPublicKey(peerId, key) {
* @returns {Promise<String>}
*/
async function getPeerPublicKey(peerId) {
- return await sql.promise(`SELECT key_data FROM peer_keys WHERE peer_id = "${peerId}" LIMIT 1`).then(res =>
+ return await db.peer_keys.where('peer_id').equals(peerId).limit(1).toArray().then(res =>
res.length > 0 ? res[0]['key_data'] : ''
);
}
@@ -182,7 +173,6 @@ function testEncryption() {
}
exports.setup = setupDatabase;
-exports.setupConn = setupDatabaseConnection;
exports.generate = generateKeys;
exports.getPrivate = getPrivateKey;
exports.getPublic = getPublicKey;
@@ -192,5 +182,3 @@ exports.check = isEncrypted;
exports.store = storePeerPublicKey;
exports.get = getPeerPublicKey;
exports.test = testEncryption;
-
-window.sql = sql; // For debugging
diff --git a/public/scripts/chat.js b/public/scripts/chat.js
index e81bd44..01377bf 100644
--- a/public/scripts/chat.js
+++ b/public/scripts/chat.js
@@ -8,12 +8,12 @@ const peerId = nanoid();
// setup encryption
(async () => {
- if (localStorage.getItem('database') === 'success' && encryption.setupConn() && await encryption.check()) {
+ encryption.setup();
+ if (localStorage.getItem('database') === 'success' && await encryption.check()) {
// TODO: Ask for passphrase
chat();
} else {
console.log('[LOG] No existing keys found! Generating...');
- encryption.setup();
(async () => await encryption.generate(peerId, 'supersecure').then(() => chat()))()
}
})();