Mailspring/packages/nylas-core/models/shared/account.js

64 lines
1.9 KiB
JavaScript
Raw Normal View History

const crypto = require('crypto');
const {JSONType} = require('../../database-types');
const {DB_ENCRYPTION_ALGORITHM, DB_ENCRYPTION_PASSWORD} = process.env;
2016-06-19 18:02:32 +08:00
module.exports = (sequelize, Sequelize) => {
const Account = sequelize.define('Account', {
name: Sequelize.STRING,
provider: Sequelize.STRING,
2016-06-19 18:02:32 +08:00
emailAddress: Sequelize.STRING,
connectionSettings: JSONType('connectionSettings'),
connectionCredentials: Sequelize.STRING,
syncPolicy: JSONType('syncPolicy'),
syncError: JSONType('syncError', {defaultValue: null}),
2016-06-19 18:02:32 +08:00
}, {
classMethods: {
associate: ({AccountToken}) => {
Account.hasMany(AccountToken, {as: 'tokens'})
},
},
instanceMethods: {
toJSON: function toJSON() {
return {
id: this.id,
2016-06-29 09:14:54 +08:00
object: 'account',
2016-06-19 18:02:32 +08:00
email_address: this.emailAddress,
2016-06-23 05:17:45 +08:00
connection_settings: this.connectionSettings,
sync_policy: this.syncPolicy,
sync_error: this.syncError,
2016-06-19 18:02:32 +08:00
}
},
2016-06-28 01:27:38 +08:00
errored: function errored() {
return this.syncError != null
2016-06-28 01:27:38 +08:00
},
setCredentials: function setCredentials(json) {
if (!(json instanceof Object)) {
throw new NylasError("Call setCredentials with JSON!")
}
const cipher = crypto.createCipher(DB_ENCRYPTION_ALGORITHM, DB_ENCRYPTION_PASSWORD)
let crypted = cipher.update(JSON.stringify(json), 'utf8', 'hex')
crypted += cipher.final('hex');
this.connectionCredentials = crypted;
},
decryptedCredentials: function decryptedCredentials() {
const decipher = crypto.createDecipher(DB_ENCRYPTION_ALGORITHM, DB_ENCRYPTION_PASSWORD)
let dec = decipher.update(this.connectionCredentials, 'hex', 'utf8')
dec += decipher.final('utf8');
try {
return JSON.parse(dec);
} catch (err) {
return null;
}
},
2016-06-19 18:02:32 +08:00
},
});
return Account;
};