2018-10-02 19:46:38 +03:00
|
|
|
const crypto = require('crypto');
|
|
|
|
const ghostBookshelf = require('./base');
|
|
|
|
const {Role} = require('./role');
|
|
|
|
|
2018-10-05 11:51:13 +03:00
|
|
|
const createSecret = () => crypto.randomBytes(64).toString('hex');
|
|
|
|
|
2018-10-02 19:46:38 +03:00
|
|
|
const ApiKey = ghostBookshelf.Model.extend({
|
|
|
|
tableName: 'api_keys',
|
|
|
|
|
|
|
|
defaults() {
|
|
|
|
// 512bit key for HS256 JWT signing
|
2018-10-05 11:51:13 +03:00
|
|
|
const secret = createSecret();
|
2018-10-02 19:46:38 +03:00
|
|
|
|
|
|
|
return {
|
|
|
|
secret
|
|
|
|
};
|
|
|
|
},
|
|
|
|
|
|
|
|
role() {
|
|
|
|
return this.belongsTo('Role');
|
|
|
|
},
|
|
|
|
|
|
|
|
// if an ApiKey does not have a related Integration then it's considered
|
|
|
|
// "internal" and shouldn't show up in the UI. Example internal API Keys
|
|
|
|
// would be the ones used for the scheduler and backup clients
|
|
|
|
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) {
|
|
|
|
const secret = createSecret();
|
|
|
|
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)
|
|
|
|
};
|