2018-10-02 19:46:38 +03:00
|
|
|
const crypto = require('crypto');
|
|
|
|
const ghostBookshelf = require('./base');
|
|
|
|
const {Role} = require('./role');
|
|
|
|
|
2019-01-04 15:39:54 +03:00
|
|
|
/*
|
|
|
|
* Uses birthday problem estimation to calculate chance of collision
|
|
|
|
* d = 16^26 // 26 char hex string
|
|
|
|
* n = 10,000,000 // 10 million
|
|
|
|
*
|
|
|
|
* (-n x (n-1)) / 2d
|
|
|
|
* 1 - e^
|
|
|
|
*
|
|
|
|
*
|
|
|
|
* 17
|
|
|
|
* ~= 4 x 10^
|
|
|
|
*
|
|
|
|
* ref: https://medium.freecodecamp.org/how-long-should-i-make-my-api-key-833ebf2dc26f
|
|
|
|
* ref: https://en.wikipedia.org/wiki/Birthday_problem#Approximations
|
|
|
|
*
|
|
|
|
* 26 char hex string = 13 bytes
|
2019-01-24 16:46:33 +03:00
|
|
|
* 64 char hex string JWT secret = 32 bytes
|
2019-01-04 15:39:54 +03:00
|
|
|
*/
|
|
|
|
const createSecret = (type) => {
|
2019-01-24 16:46:33 +03:00
|
|
|
const bytes = type === 'content' ? 13 : 32;
|
2019-01-04 15:39:54 +03:00
|
|
|
return crypto.randomBytes(bytes).toString('hex');
|
|
|
|
};
|
2018-10-05 11:51:13 +03:00
|
|
|
|
2018-10-02 19:46:38 +03:00
|
|
|
const ApiKey = ghostBookshelf.Model.extend({
|
|
|
|
tableName: 'api_keys',
|
|
|
|
|
|
|
|
defaults() {
|
2019-01-04 15:39:54 +03:00
|
|
|
const secret = createSecret(this.get('type'));
|
2018-10-02 19:46:38 +03:00
|
|
|
|
|
|
|
return {
|
|
|
|
secret
|
|
|
|
};
|
|
|
|
},
|
|
|
|
|
|
|
|
role() {
|
|
|
|
return this.belongsTo('Role');
|
|
|
|
},
|
|
|
|
|
|
|
|
integration() {
|
|
|
|
return this.belongsTo('Integration');
|
|
|
|
},
|
|
|
|
|
2018-10-14 12:54:10 +03:00
|
|
|
onSaving(model, attrs, options) {
|
2018-10-02 19:46:38 +03:00
|
|
|
ghostBookshelf.Model.prototype.onSaving.apply(this, arguments);
|
|
|
|
|
|
|
|
// enforce roles which are currently hardcoded
|
|
|
|
// - admin key = Adminstrator role
|
|
|
|
// - content key = no role
|
|
|
|
if (this.hasChanged('type') || this.hasChanged('role_id')) {
|
|
|
|
if (this.get('type') === 'admin') {
|
2018-10-14 12:54:10 +03:00
|
|
|
return Role.findOne({name: 'Admin Integration'}, Object.assign({}, options, {columns: ['id']}))
|
2018-10-02 19:46:38 +03:00
|
|
|
.then((role) => {
|
|
|
|
this.set('role_id', role.get('id'));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.get('type') === 'content') {
|
|
|
|
this.set('role_id', null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-10-05 11:51:13 +03:00
|
|
|
}, {
|
|
|
|
refreshSecret(data, options) {
|
2019-01-24 16:46:33 +03:00
|
|
|
const secret = createSecret(data.type);
|
2018-10-05 11:51:13 +03:00
|
|
|
return this.edit(Object.assign({}, data, {secret}), options);
|
|
|
|
}
|
2018-10-02 19:46:38 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
const ApiKeys = ghostBookshelf.Collection.extend({
|
|
|
|
model: ApiKey
|
|
|
|
});
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
ApiKey: ghostBookshelf.model('ApiKey', ApiKey),
|
|
|
|
ApiKeys: ghostBookshelf.collection('ApiKeys', ApiKeys)
|
|
|
|
};
|