Skip to content

Commit

Permalink
ensure private devices of other users can't be added to experiments
Browse files Browse the repository at this point in the history
  • Loading branch information
timcowlishaw committed Aug 12, 2024
1 parent ad7a4dc commit a50424a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
12 changes: 12 additions & 0 deletions app/models/experiment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ class Experiment < ApplicationRecord
validates_presence_of :name, :owner
validates_inclusion_of :is_test, in: [true, false]

validate :cannot_add_private_devices_of_other_users

def self.ransackable_attributes(auth_object = nil)
["created_at", "description", "ends_at", "id", "is_test", "name", "owner_id", "starts_at", "status", "updated_at"]
end
Expand All @@ -13,4 +15,14 @@ def self.ransackable_attributes(auth_object = nil)
def active?
(!starts_at || Time.now >= starts_at) && (!ends_at || Time.now <= ends_at)
end

private

def cannot_add_private_devices_of_other_users
private_devices = devices.select { |device| device.is_private? && device.owner != self.owner }
if private_devices.any?
ids = private_devices.map(&:id).join(", ")
errors.add(:devices, "can't contain private devices owned by other users (ids: #{ids})")
end
end
end
32 changes: 32 additions & 0 deletions spec/models/experiment_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,38 @@

RSpec.describe Experiment, type: :model do


describe "validations" do
context "when the experiment has private devices owned by the same owner" do
it "is valid" do
owner = create(:user)
device = create(:device, is_private: true, owner: owner)
experiment = build(:experiment, owner: owner, devices: [device])
expect(experiment).to be_valid
end
end

context "when the experiment has public devices owned by another user" do
it "is valid" do
device_owner = create(:user)
experiment_owner = create(:user)
device = create(:device, is_private: false, owner: device_owner)
experiment = build(:experiment, owner: experiment_owner, devices: [device])
expect(experiment).to be_valid
end
end

context "when the experiment has private devices owned by another user" do
it "is not valid" do
device_owner = create(:user)
experiment_owner = create(:user)
device = create(:device, is_private: true, owner: device_owner)
experiment = build(:experiment, owner: experiment_owner, devices: [device])
expect(experiment).not_to be_valid
end
end
end

describe "#is_active?" do
context "when the experiment has neither start or end times" do
it "is active" do
Expand Down

0 comments on commit a50424a

Please sign in to comment.