Merge pull request #4830 from jaswilli/find-by-role

Fixup finding user by role name
This commit is contained in:
Hannah Wolfe 2015-01-21 11:01:44 +00:00
commit 8454a1c0bb
2 changed files with 39 additions and 11 deletions

View File

@ -357,7 +357,10 @@ User = ghostBookshelf.Model.extend({
*/
findOne: function (data, options) {
var query,
status;
status,
lookupRole = data.role;
delete data.role;
data = _.extend({
status: 'active'
@ -370,17 +373,19 @@ User = ghostBookshelf.Model.extend({
options.withRelated = _.union(options.withRelated, options.include);
// Support finding by role
if (data.role) {
options.withRelated = [{
roles: function (qb) {
qb.where('name', data.role);
}
}];
delete data.role;
}
if (lookupRole) {
options.withRelated = _.union(options.withRelated, ['roles']);
options.include = _.union(options.include, ['roles']);
// We pass include to forge so that toJSON has access
query = this.forge(data, {include: options.include});
query = this.forge(data, {include: options.include});
query.query('join', 'roles_users', 'users.id', '=', 'roles_users.id');
query.query('join', 'roles', 'roles_users.role_id', '=', 'roles.id');
query.query('where', 'roles.name', '=', lookupRole);
} else {
// We pass include to forge so that toJSON has access
query = this.forge(data, {include: options.include});
}
data = this.filterData(data);

View File

@ -301,6 +301,29 @@ describe('User Model', function run() {
}).catch(done);
});
it('can findOne by role name', function (done) {
return testUtils.fixtures.createExtraUsers().then(function () {
return Promise.join(UserModel.findOne({role: 'Owner'}), UserModel.findOne({role: 'Editor'}));
}).then(function (results) {
var owner = results[0],
editor = results[1];
should.exist(owner);
should.exist(editor);
owner = owner.toJSON();
editor = editor.toJSON();
should.exist(owner.roles);
should.exist(editor.roles);
owner.roles[0].name.should.equal('Owner');
editor.roles[0].name.should.equal('Editor');
done();
}).catch(done);
});
it('can edit', function (done) {
var firstUser = 1;