Skip to content

Commit

Permalink
Merge pull request #7 from manyfold3d/upsert-permissions
Browse files Browse the repository at this point in the history
Overwrite existing relation when changing permission level.
  • Loading branch information
Floppy authored Aug 30, 2024
2 parents 5ae0eeb + 381aa3b commit 5578783
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 1 deletion.
4 changes: 3 additions & 1 deletion app/models/concerns/caber/object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ def self.can_grant_permissions_to(model)
end

def grant_permission_to(permission, subject)
Caber::Relation.create!(subject: subject, permission: permission, object: self)
rel = Caber::Relation.find_or_initialize_by(subject: subject, object: self)
rel.permission = permission
rel.save!
end

def grants_permission_to?(permission, subject)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ class CreateCaberRelations < ActiveRecord::Migration<%= migration_version %>
t.references :object, polymorphic: true, null: false

t.timestamps
t.index [:subject_id, :subject_type, :object_id, :object_type], unique: true
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def change
t.references :object, polymorphic: true, null: false

t.timestamps
t.index [:subject_id, :subject_type, :object_id, :object_type], unique: true
end
end
end
1 change: 1 addition & 0 deletions spec/dummy/db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["object_type", "object_id"], name: "index_caber_relations_on_object"
t.index ["subject_id", "subject_type", "object_id", "object_type"], name: "idx_on_subject_id_subject_type_object_id_object_typ_a279b094be", unique: true
t.index ["subject_type", "subject_id"], name: "index_caber_relations_on_subject"
end

Expand Down
21 changes: 21 additions & 0 deletions spec/models/caber/relation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,27 @@
end
end

context "changing permissions" do
before do
object.grant_permission_to "viewer", alice
end

it "should update the existing permission relation" do
expect { object.grant_permission_to("editor", alice) }
.not_to change(Caber::Relation, :count)
end

it "should store the new permission" do
object.grant_permission_to("editor", alice)
expect(alice.has_permission_on?("editor", object)).to be true
end

it "should overwrite the old permission" do
object.grant_permission_to("editor", alice)
expect(alice.has_permission_on?("viewer", object)).to be false
end
end

context "removing permissions on object/subject removal" do
before do
object.grant_permission_to "viewer", alice
Expand Down

0 comments on commit 5578783

Please sign in to comment.