Skip to content

Commit

Permalink
fix(extra): fixes edge cases when building query to database (#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
vonagam authored and stalniy committed Jul 4, 2019
1 parent 491099b commit 437d4e7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
27 changes: 27 additions & 0 deletions packages/casl-ability/spec/query.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ describe('rulesToQuery', () => {
expect(query).to.be.null
})

it('returns non-`null` if there is at least one regular rule after last inverted one without conditions', () => {
const ability = AbilityBuilder.define((can, cannot) => {
can('read', 'Post', { public: true })
cannot('read', 'Post', { author: 321 })
cannot('read', 'Post')
can('read', 'Post', { author: 123 })
})
const query = toQuery(ability, 'read', 'Post')

expect(query).to.deep.equal({
$or: [
{ author: 123 }
]
})
})

it('OR-es conditions for regular rules', () => {
const ability = AbilityBuilder.define(can => {
can('read', 'Post', { status: 'draft', createdBy: 'someoneelse' })
Expand Down Expand Up @@ -123,4 +139,15 @@ describe('rulesToQuery', () => {
]
})
})

it('returns empty `$and` part if inverted rule with conditions defined before regular rule without conditions', () => {
const ability = AbilityBuilder.define((can, cannot) => {
can('read', 'Post', { author: 123 })
cannot('read', 'Post', { private: true })
can('read', 'Post')
})
const query = toQuery(ability, 'read', 'Post')

expect(Object.keys(query)).to.be.empty
})
})
16 changes: 5 additions & 11 deletions packages/casl-ability/src/extra.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { setByPath } from './utils';

export function rulesToQuery(ability, action, subject, convert) {
const query = {};
const ignoreOperators = {};
const rules = ability.rulesFor(action, subject);

for (let i = 0; i < rules.length; i++) {
Expand All @@ -11,23 +10,18 @@ export function rulesToQuery(ability, action, subject, convert) {

if (!rule.conditions) {
if (rule.inverted) {
return null;
}

if (query[op]) {
break;
} else {
delete query[op];
return query;
}

ignoreOperators[op] = true;
} else if (!ignoreOperators.hasOwnProperty(op)) {
} else {
query[op] = query[op] || [];
query[op].push(convert(rule));
}
}

const isOnlyInvertedRules = query.$and && query.$and.length === rules.length;

return rules.length === 0 || isOnlyInvertedRules ? null : query;
return query.$or ? query : null;
}

export function rulesToFields(ability, action, subject) {
Expand Down

0 comments on commit 437d4e7

Please sign in to comment.