コード例 #1
0
    async function getKey(profileDirectory, masterPassword) {
        const key4FilePath = path.join(profileDirectory, 'key4.db');
        if (!fs.existsSync(key4FilePath)) {
            throw new Error('key4.db was not found in this profile directory.');
        }

        const masterPasswordBytes = forge.util.encodeUtf8(masterPassword || '');
        const key4File = fs.readFileSync(key4FilePath);
        const key4Db = new SQL.Database(key4File);
        const metaData = key4Db.exec('SELECT item1, item2 FROM metadata WHERE id = \'password\';');
        if (metaData && metaData.length && metaData[0].values && metaData[0].values.length) {
            const globalSalt = toByteString(metaData[0].values[0][0].buffer);
            const item2 = toByteString(metaData[0].values[0][1].buffer);
            const item2Asn1 = forge.asn1.fromDer(item2);
            const item2Salt = item2Asn1.value[0].value[1].value[0].value;
            const item2Data = item2Asn1.value[1].value;
            const item2Value = decryptKey(globalSalt, masterPasswordBytes, item2Salt, item2Data);
            if (item2Value && item2Value.data === 'password-check') {
                const nssData = key4Db.exec('SELECT a11 FROM nssPrivate WHERE a11 IS NOT NULL;');
                if (nssData && nssData.length && nssData[0].values && nssData[0].values.length) {
                    const a11 = toByteString(nssData[0].values[0][0].buffer);
                    const a11Asn1 = forge.asn1.fromDer(a11);
                    const a11Salt = a11Asn1.value[0].value[1].value[0].value;
                    const a11Data = a11Asn1.value[1].value;
                    const a11Value = decryptKey(globalSalt, masterPasswordBytes, a11Salt, a11Data);
                    return forge.util.createBuffer(a11Value).getBytes(24);
                }
            } else {
                // TODO: Support key3.db?
                throw new Error('Master password incorrect.');
            }
        }

        throw new Error('Not able to get key from profile directory.');
    }
コード例 #2
0
function onFlush(time_stamp, metrics) {
    console.log(time_stamp);
    console.log(metrics);
    //logger('x packets received, writing to file.sqlite...');

    var db = new sql.Database(fs.readFileSync(options.sqliteFile));

    function create(table) {
        db.run('CREATE TABLE IF NOT EXISTS ' + table
                + '(timestamp TEXT, name TEXT, value INT);');
    }
    function insert(table, name, value) {
        db.run('INSERT INTO ' + table + ' VALUES("'
                    + time_stamp + '","' + name + '",' + value + ');');
    }

    ['counters', 'gauges', 'timers', 'sets'].forEach((table) => {
        var names = [];
        // filter out blacklisted metrics
        for (var name in metrics[table])
            if (blacklist.indexOf(name) === -1) names.push(name);

        // don't create table if no entry
        if (names.length > 0) create(table);

        names.forEach((name) => {
            insert(table, name, metrics[table][name]);
        });
    });

    // not efficient :(
    fs.writeFileSync(options.sqliteFile, new Buffer(db.export()));
    db.close();
}
コード例 #3
0
ファイル: sqlite.js プロジェクト: shiv3/rakugaki
 xhr.onload = function(e) {
   var uInt8Array = new Uint8Array(this.response);
   var db = new SQL.Database(uInt8Array);
   var contents = db.exec("SELECT ImageData FROM CanvasPreview");
   let imagedata = contents[0].values[0];
   var b64encoded = bufferToBase64(imagedata);
   console.log(imagedata)
   console.log(b64encoded);
   // contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
 };
コード例 #4
0
ファイル: server.js プロジェクト: gaearon/food-lookup-demo
app.get('/api/food', (req, res) => {
  const param = req.query.q;

  if (!param) {
    res.json({
      error: 'Missing required parameter `q`',
    });
    return;
  }

  const r = db.exec(`
    select ${COLUMNS.join(', ')} from entries
    where description like '%${param}%'
    limit 100
  `);

  if (r[0]) {
    res.json(
      r[0].values.map((entry) => {
        const e = {};
        COLUMNS.forEach((c, idx) => {
          e[c] = entry[idx];
        });
        return e;
      }),
    );
  } else {
    res.json([]);
  }
});
コード例 #5
0
ファイル: db.js プロジェクト: jleelove/card_game_server
	this.userExists(data.username,function(err,response){
			if(!response){
				db.run("INSERT INTO users (username,password,lastlogin,loggedin) VALUES('"+data.username+"','"+data.pass+"','"+current+"',1)");
				saveDB();
				_callback(null,true);
			}else{
					_callback("User already exists",false)
			}
	});
コード例 #6
0
app.get("/api/food", (req, res) => {
  const param = req.query.q;

  if (!param) {
    res.json({
      error: "Missing required parameter `q`"
    });
    return;
  }

  // WARNING: Not for production use! The following statement
  // is not protected against SQL injections.
  const r = db.exec(
    `
    select ${COLUMNS.join(", ")} from entries
    where description like '%${param}%'
    limit 100
  `
  );

  if (r[0]) {
    res.json(
      r[0].values.map(entry => {
        const e = {};
        COLUMNS.forEach((c, idx) => {
          // combine fat columns
          if (c.match(/^fa_/)) {
            e.fat_g = e.fat_g || 0.0;
            e.fat_g = (parseFloat(e.fat_g, 10) +
              parseFloat(entry[idx], 10)).toFixed(2);
          } else {
            e[c] = entry[idx];
          }
        });
        return e;
      })
    );
  } else {
    res.json([]);
  }
});
コード例 #7
0
ファイル: backup.js プロジェクト: byesoft/seals
function saveChatHistory (uid, messageList) {
  const db = new sqlite.Database()
  db.run('CREATE TABLE message ("time" DATETIME, "from" INT, "to" INT, "content" TEXT, "media" TEXT)')
  db.run('BEGIN TRANSACTION')
  const stmt = db.prepare('INSERT INTO message VALUES(?, ?, ?, ?, ?)')
  for (let i = 0; i < messageList.length; i++) {
    const message = messageList[i]
    stmt.run([message.time
      , message.from
      , message.to
      , JSON.stringify(message.content)
      , JSON.stringify(message.media)
    ])
  }
  db.run('COMMIT TRANSACTION')
  const dbBuffer = new Buffer(db.export())
  fs.writeFileSync(`${options.savePath}/${uid}/${uid}.db`, dbBuffer)
}
コード例 #8
0
ファイル: balsamiq_viewer.js プロジェクト: axilleas/gitlabhq
  getResource(resourceID) {
    const resources = this.database.exec(`SELECT * FROM resources WHERE id = '${resourceID}'`);

    return resources[0];
  }
コード例 #9
0
ファイル: balsamiq_viewer.js プロジェクト: axilleas/gitlabhq
  getPreviews() {
    const thumbnails = this.database.exec('SELECT * FROM thumbnails');

    return thumbnails[0].values.map(BalsamiqViewer.parsePreview);
  }
コード例 #10
0
/**
 * A SQLite database helper.
 *
 * @param schemaPath {string}
 * @param dbPath {string}
 * @constructor
 */
function SQLiteHelper (schemaPath, dbPath) {

    let dbFilePath = dbPath,
        dbDirPath = path.dirname(dbFilePath),
        sql;

    /**
     * Saves a sql database to the disk.
     *
     * @param sql {Database}
     */
    function saveDB (sql) {
        let data = sql.export();
        let buffer = new Buffer(data);

        mkdirp.sync(dbDirPath, '0755');
        fs.writeFileSync(dbFilePath, buffer);
    }

    /**
     * Prefixes object params with ':'.
     * If something other than an object is given the will be returned without being changed.
     *
     * @param params {[]|{}|string}
     * @returns {*} returns the updated params object
     */
    function normalizeParams(params) {
        if (params && params.constructor !== Array && typeof params === 'object') {
            params = _.mapKeys(params, function (value, key) {
                return ':' + _.trimStart(key, ':');
            });
        }
        return params;
    }

    /**
     * Executes a command returning the results.
     *
     * @param query {string} the query string
     * @param params {[]|{}} the parameters to be bound to the query
     * @returns {[]} an array of rows
     */
    function query (query, params) {
        let rows = [];
        let stmt = sql.prepare(query);
        params = normalizeParams(params);
        stmt.bind(params);
        while(stmt.step()) {
            rows.push(stmt.getAsObject());
        }
        stmt.free();
        return rows;
    }

    /**
     * Executes a command ignoring the results.
     *
     * @param query {string} the run string
     * @param params {[]|{}} the parameters to be bound to the query
     */
    function run(query, params) {
        let stmt = sql.prepare(query);
        params = normalizeParams(params);
        stmt.run(params);
        stmt.free();
    }

    if (!fs.existsSync(dbFilePath)) {
        let schema = fs.readFileSync(schemaPath);

        sql = new SQL.Database();
        sql.run(schema);

        saveDB(sql);
    } else {
        let buffer = fs.readFileSync(dbFilePath);

        sql = new SQL.Database(buffer);
    }
    
    return {query: query, save: saveDB.bind(null, sql), run: run};
}
コード例 #11
0
ファイル: db.js プロジェクト: jleelove/card_game_server
df.verify = function(data,_callback){
	var results = db.exec("SELECT id from users where username='******' AND password='******'");
	if(results.length>0)_callback(null,true);
	else
	_callback(null,false);
}
コード例 #12
0
ファイル: db.js プロジェクト: jleelove/card_game_server
function saveDB(){
	var data = db.export();
	var buffer = new Buffer(data);
	fs.writeFileSync("dbase.sqlite", buffer);
}
コード例 #13
0
ファイル: db.js プロジェクト: jleelove/card_game_server
df.userExists = function(username,_callback){
	var results = db.exec("SELECT id from users where username='******'");
	if(results.length>0)_callback(null,true);
	else
	_callback(null,false);
}