2016-06-22 09:29:58 +08:00
|
|
|
const crypto = require('crypto');
|
|
|
|
const {JSONType} = require('../../database-types');
|
|
|
|
|
|
|
|
const algorithm = 'aes-256-ctr';
|
|
|
|
const password = 'd6F3Efeq';
|
|
|
|
|
2016-06-19 18:02:32 +08:00
|
|
|
module.exports = (sequelize, Sequelize) => {
|
|
|
|
const Account = sequelize.define('Account', {
|
|
|
|
emailAddress: Sequelize.STRING,
|
2016-06-22 09:29:58 +08:00
|
|
|
connectionSettings: JSONType('connectionSettings'),
|
|
|
|
connectionCredentials: Sequelize.STRING,
|
|
|
|
syncPolicy: JSONType('syncPolicy'),
|
2016-06-19 18:02:32 +08:00
|
|
|
}, {
|
|
|
|
classMethods: {
|
|
|
|
associate: ({AccountToken}) => {
|
|
|
|
Account.hasMany(AccountToken, {as: 'tokens'})
|
|
|
|
},
|
|
|
|
},
|
|
|
|
instanceMethods: {
|
|
|
|
toJSON: function toJSON() {
|
|
|
|
return {
|
|
|
|
id: this.id,
|
|
|
|
email_address: this.emailAddress,
|
|
|
|
}
|
|
|
|
},
|
2016-06-22 09:29:58 +08:00
|
|
|
|
|
|
|
setCredentials: function setCredentials(json) {
|
|
|
|
if (!(json instanceof Object)) {
|
|
|
|
throw new Error("Call setCredentials with JSON!")
|
|
|
|
}
|
|
|
|
const cipher = crypto.createCipher(algorithm, password)
|
|
|
|
let crypted = cipher.update(JSON.stringify(json), 'utf8', 'hex')
|
|
|
|
crypted += cipher.final('hex');
|
|
|
|
|
|
|
|
this.connectionCredentials = crypted;
|
|
|
|
},
|
|
|
|
|
|
|
|
decryptedCredentials: function decryptedCredentials() {
|
|
|
|
const decipher = crypto.createDecipher(algorithm, 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;
|
|
|
|
};
|