snappymail/dev/Stores/User/Pgp.js

123 lines
2.2 KiB
JavaScript
Raw Normal View History

2015-02-01 23:44:44 +08:00
(function () {
'use strict';
2015-02-03 07:58:58 +08:00
var
2015-02-22 06:00:51 +08:00
_ = require('_'),
ko = require('ko'),
Utils = require('Common/Utils')
2015-02-03 07:58:58 +08:00
;
2015-02-01 23:44:44 +08:00
/**
* @constructor
*/
function PgpUserStore()
{
2015-02-03 07:58:58 +08:00
this.capaOpenPGP = ko.observable(false);
2015-02-01 23:44:44 +08:00
this.openpgp = null;
2015-02-03 07:58:58 +08:00
this.openpgpkeys = ko.observableArray([]);
this.openpgpKeyring = null;
2015-02-01 23:44:44 +08:00
2015-02-03 07:58:58 +08:00
this.openpgpkeysPublic = this.openpgpkeys.filter(function (oItem) {
return !!(oItem && !oItem.isPrivate);
});
2015-02-01 23:44:44 +08:00
2015-02-03 07:58:58 +08:00
this.openpgpkeysPrivate = this.openpgpkeys.filter(function (oItem) {
return !!(oItem && oItem.isPrivate);
});
}
2015-02-01 23:44:44 +08:00
/**
* @return {boolean}
*/
PgpUserStore.prototype.isSupported = function ()
{
return !!this.openpgp;
};
2015-02-22 06:00:51 +08:00
PgpUserStore.prototype.findPublicKeyByHex = function (sHash)
{
return _.find(this.openpgpkeysPublic(), function (oItem) {
return oItem && sHash === oItem.id;
});
};
PgpUserStore.prototype.findPublicKeysByEmail = function (sEmail)
{
var self = this;
return _.compact(_.map(this.openpgpkeysPublic(), function (oItem) {
var oKey = null;
if (oItem && sEmail === oItem.email)
{
try
{
oKey = self.openpgp.key.readArmored(oItem.armor);
if (oKey && !oKey.err && oKey.keys && oKey.keys[0])
{
return oKey.keys[0];
}
}
catch (e) {}
}
return null;
}));
};
/**
* @param {string} sEmail
* @param {string=} sPassword
* @returns {?}
*/
PgpUserStore.prototype.findPrivateKeyByEmail = function (sEmail, sPassword)
{
var
oPrivateKey = null,
oKey = _.find(this.openpgpkeysPrivate(), function (oItem) {
return oItem && sEmail === oItem.email;
})
;
if (oKey)
{
try
{
oPrivateKey = this.openpgp.key.readArmored(oKey.armor);
if (oPrivateKey && !oPrivateKey.err && oPrivateKey.keys && oPrivateKey.keys[0])
{
oPrivateKey = oPrivateKey.keys[0];
oPrivateKey.decrypt(Utils.pString(sPassword));
}
else
{
oPrivateKey = null;
}
}
catch (e)
{
oPrivateKey = null;
}
}
return oPrivateKey;
};
/**
* @param {string=} sPassword
* @returns {?}
*/
PgpUserStore.prototype.findSelfPrivateKey = function (sPassword)
{
return this.findPrivateKeyByEmail(require('Stores/User/Account').email(), sPassword);
};
2015-02-01 23:44:44 +08:00
module.exports = new PgpUserStore();
}());