Improve roles in database to work with Bookshelf

This commit is contained in:
Aurelsicoko 2018-01-23 18:54:17 +01:00
parent 187f6cb748
commit 8f85d85349
8 changed files with 77 additions and 54 deletions

View File

@ -227,7 +227,7 @@ module.exports = function(strapi) {
// Build associations key // Build associations key
utilsModels.defineAssociations( utilsModels.defineAssociations(
definition.globalName, model.toLowerCase(),
definition, definition,
details, details,
name name

View File

@ -205,7 +205,7 @@ module.exports = function (strapi) {
const verbose = _.get(utilsModels.getNature(details, name, undefined, model.toLowerCase()), 'verbose') || ''; const verbose = _.get(utilsModels.getNature(details, name, undefined, model.toLowerCase()), 'verbose') || '';
// Build associations key // Build associations key
utilsModels.defineAssociations(model, definition, details, name); utilsModels.defineAssociations(model.toLowerCase(), definition, details, name);
if (_.isEmpty(verbose)) { if (_.isEmpty(verbose)) {
definition.loadedModel[name].type = utils(instance).convertType(details.type); definition.loadedModel[name].type = utils(instance).convertType(details.type);

View File

@ -11,9 +11,13 @@ module.exports = {
qb.orderBy(params.sort); qb.orderBy(params.sort);
} }
if (params.skip) {
qb.offset(_.toNumber(params.skip)); qb.offset(_.toNumber(params.skip));
}
if (params.limit) {
qb.limit(_.toNumber(params.limit)); qb.limit(_.toNumber(params.limit));
}
}).fetchAll({ }).fetchAll({
withRelated: this.associations.map(x => x.alias) withRelated: this.associations.map(x => x.alias)
}); });
@ -39,14 +43,14 @@ module.exports = {
create: async function (params) { create: async function (params) {
const entry = await this const entry = await this
.forge() .forge(Object.keys(params.values).reduce((acc, current) => {
.save(Object.keys(params.values).reduce((acc, current) => {
if (this._attributes[current].type) { if (this._attributes[current].type) {
acc[current] = params.values[current]; acc[current] = params.values[current];
} }
return acc; return acc;
}, {})) }, {}))
.save()
.catch((err) => { .catch((err) => {
if (err.detail) { if (err.detail) {
const field = _.last(_.words(err.detail.split('=')[0])); const field = _.last(_.words(err.detail.split('=')[0]));

View File

@ -1,42 +1,49 @@
const _ = require('lodash'); const _ = require('lodash');
module.exports = { module.exports = {
find: async function (params) { find: async function (params = {}, populate) {
const records = this.query(function(qb) { const records = await this.query(function(qb) {
_.forEach(params.where, (where, key) => { _.forEach(params.where, (where, key) => {
qb.where(key, where[0].symbol, where[0].value); qb.where(key, where[0].symbol, where[0].value);
}); });
if (params.sort) { if (params.sort) {
qb.orderBy(params.sort); qb.orderByRaw(params.sort);
} }
if (params.start) {
qb.offset(params.start); qb.offset(params.start);
}
if (params.limit) {
qb.limit(params.limit); qb.limit(params.limit);
}
}).fetchAll({ }).fetchAll({
withRelated: _.keys(_.groupBy(_.reject(this.associations, {autoPopulate: false}), 'alias')) withRelated: populate || _.keys(_.groupBy(_.reject(this.associations, { autoPopulate: false }), 'alias'))
}); });
return records ? records.toJSON() : records; return records ? records.toJSON() : records;
}, },
count: async function (params) { count: async function (params = {}) {
return await this return await this
.forge() .where(params)
.count(); .count();
}, },
findOne: async function (params) { findOne: async function (params, populate) {
if (_.get(params, '_id')) { const primaryKey = params[this.primaryKey] || params.id;
params.id = params._id;
delete params._id; if (primaryKey) {
params = {
[this.primaryKey]: primaryKey
}
} }
const record = await this const record = await this
.forge(params) .forge(params)
.fetch({ .fetch({
withRelated: this.associations.map(x => x.alias) withRelated: populate || this.associations.map(x => x.alias)
}); });
return record ? record.toJSON() : record; return record ? record.toJSON() : record;
@ -46,7 +53,7 @@ module.exports = {
return this return this
.forge() .forge()
.save(Object.keys(params).reduce((acc, current) => { .save(Object.keys(params).reduce((acc, current) => {
if (_.get(this, ['_attributes', current, 'type'])) { if (_.get(this._attributes, [current, 'type']) || _.get(this._attributes, [current, 'model'])) {
acc[current] = params[current]; acc[current] = params[current];
} }
@ -72,6 +79,12 @@ module.exports = {
if (primaryKey) { if (primaryKey) {
search = { search = {
[this.primaryKey]: primaryKey [this.primaryKey]: primaryKey
};
} else {
const entry = await module.exports.findOne.call(this, search);
search = {
[this.primaryKey]: entry[this.primaryKey] || entry.id
} }
} }
@ -107,8 +120,8 @@ module.exports = {
addPermission: async function (params) { addPermission: async function (params) {
return this return this
.forge() .forge(params)
.save(params); .save();
}, },
removePermission: async function (params) { removePermission: async function (params) {

View File

@ -17,11 +17,12 @@ module.exports = {
}, },
findOne: async function (params, populate) { findOne: async function (params, populate) {
if (!params[this.primaryKey] && params.id) { const primaryKey = params[this.primaryKey] || params.id;
params[this.primaryKey] = params.id;
delete params.id; if (primaryKey) {
} else if (params.id) { params = {
delete params.id; [this.primaryKey]: primaryKey
}
} }
return this return this

View File

@ -158,13 +158,14 @@ module.exports = {
return ctx.badRequest(null, ctx.request.admin ? [{ messages: [{ id: 'Auth.form.error.password.format' }] }] : 'Your password cannot contain more than three times the symbol `$`.'); return ctx.badRequest(null, ctx.request.admin ? [{ messages: [{ id: 'Auth.form.error.password.format' }] }] : 'Your password cannot contain more than three times the symbol `$`.');
} }
// Retrieve root role.
const root = await strapi.query('role', 'users-permissions').findOne({ type: 'root' }, ['users']);
// First, check if the user is the first one to register as admin. // First, check if the user is the first one to register as admin.
const hasAdmin = await strapi.query('user', 'users-permissions').count(strapi.utils.models.convertParams('user', { type: 'root' })); const hasAdmin = root.users.length > 0;
// Check if the user is the first to register // Check if the user is the first to register
const role = hasAdmin < 1 ? const role = hasAdmin === false ? root : await strapi.query('role', 'users-permissions').findOne({ type: 'guest' }, []);
await strapi.query('role', 'users-permissions').findOne({ type: 'root' }, []):
await strapi.query('role', 'users-permissions').findOne({ type: 'guest' }, []);
if (!role) { if (!role) {
return ctx.badRequest(null, ctx.request.admin ? [{ messages: [{ id: 'Auth.form.error.role.notFound' }] }] : 'Impossible to find the root role.'); return ctx.badRequest(null, ctx.request.admin ? [{ messages: [{ id: 'Auth.form.error.role.notFound' }] }] : 'Impossible to find the root role.');
@ -180,7 +181,6 @@ module.exports = {
jwt: strapi.plugins['users-permissions'].services.jwt.issue(user), jwt: strapi.plugins['users-permissions'].services.jwt.issue(user),
user: _.omit(user.toJSON ? user.toJSON() : user, ['password', 'resetPasswordToken']) user: _.omit(user.toJSON ? user.toJSON() : user, ['password', 'resetPasswordToken'])
}); });
} catch(err) { } catch(err) {
const adminError = _.includes(err.message, 'username') ? 'Auth.form.error.username.taken' : 'Auth.form.error.email.taken'; const adminError = _.includes(err.message, 'username') ? 'Auth.form.error.username.taken' : 'Auth.form.error.email.taken';

View File

@ -17,7 +17,7 @@ module.exports = {
return new Error('This feature requires to install the Content Manager plugin'); return new Error('This feature requires to install the Content Manager plugin');
} }
const role = await strapi.query('role', 'users-permissions').create(_.omit(params, ['users', 'permissions'])); const role = await strapi.query('role', 'users-permissions').create(_.omit(params, ['users', 'permissions', 'type']));
const arrayOfPromises = Object.keys(params.permissions).reduce((acc, type) => { const arrayOfPromises = Object.keys(params.permissions).reduce((acc, type) => {
Object.keys(params.permissions[type].controllers).forEach(controller => { Object.keys(params.permissions[type].controllers).forEach(controller => {
@ -53,6 +53,10 @@ module.exports = {
throw new Error('Cannot found this role'); throw new Error('Cannot found this role');
} }
if (role.type === 'root') {
return new Error(`You cannot delete the root admin role.`);
}
// Move users to guest role. // Move users to guest role.
const arrayOfPromises = role.users.reduce((acc, user) => { const arrayOfPromises = role.users.reduce((acc, user) => {
acc.push(strapi.query('user', 'users-permissions').update({ acc.push(strapi.query('user', 'users-permissions').update({
@ -149,7 +153,7 @@ module.exports = {
// Group by `type`. // Group by `type`.
role.permissions = role.permissions.reduce((acc, permission) => { role.permissions = role.permissions.reduce((acc, permission) => {
_.set(acc, `${permission.type}.controllers.${permission.controller}.${permission.action}`, { _.set(acc, `${permission.type}.controllers.${permission.controller}.${permission.action}`, {
enabled: permission.enabled, enabled: _.toNumber(permission.enabled) == true,
policy: permission.policy policy: permission.policy
}); });
@ -339,6 +343,7 @@ module.exports = {
arrayOfPromises.push(this.updateUserRole(user, guest._id || guest.id)); arrayOfPromises.push(this.updateUserRole(user, guest._id || guest.id));
}); });
return Promise.all(arrayOfPromises); return Promise.all(arrayOfPromises);
}, },