Skip to content

Commit

Permalink
Merge pull request #5 from manyfold3d/granted-to
Browse files Browse the repository at this point in the history
Add ability to finding objects that subjects have some permission on
  • Loading branch information
Floppy authored Aug 29, 2024
2 parents cb8c16f + 250df07 commit 55f49c5
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,14 @@ document.revoke_permission("viewer", user)
document.revoke_all_permissions(user)
```

### Finding objects

You can get lists of objects that a user has some permission on:

```
Document.granted_to "viewer", user
# => All the documents that user has "viewer" permission on
```

## Development

Expand Down
8 changes: 8 additions & 0 deletions app/models/concerns/caber/object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ module Caber::Object
def self.can_grant_permissions_to(model)
has_many :"permitted_#{model.name.pluralize.parameterize}", through: :caber_relations, source: :subject, source_type: model.name
end

scope :granted_to, ->(permission, subject) {
includes(:caber_relations).where(
"caber_relations.subject_id": subject.id,
"caber_relations.subject_type": subject.class.name,
"caber_relations.permission": permission
)
}
end

def grant_permission_to(permission, subject)
Expand Down
12 changes: 12 additions & 0 deletions spec/models/caber/relation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@
it "includes Alice in a list of users with viewer permission for the object" do
expect(object.permitted_users.with_permission("viewer")).to include alice
end

it "can get a list of objects that Alice has permission on" do
expect(Document.granted_to("viewer", alice)).to include object
end

it "can get a list of objects that Alice one of many permissions on" do
expect(Document.granted_to(["viewer", "owner"], alice)).to include object
end
end

context "with multiple objects" do
Expand All @@ -61,6 +69,10 @@
it "does not include second (ungranted) object in Alices permitted object list" do
expect(alice.permitted_documents.with_permission("viewer")).not_to include object_two
end

it "does not include second object in list of objects that Alice has permission on" do
expect(Document.granted_to("viewer", alice)).not_to include object_two
end
end

context "checking more than one permission at once" do
Expand Down

0 comments on commit 55f49c5

Please sign in to comment.