Skip to content

Commit

Permalink
auth: tighten the index on EstablishmentUserRole
Browse files Browse the repository at this point in the history
We were scoping the uniqueness of the role to the user and
establishment, which meant you could have:

- user 1, etab X, role: dir
- user 1, etab X, role: authorised
- user 1, etab X, role: anything

Tighten the index by making the unique index enforce one user per
establishment instead.
  • Loading branch information
freesteph committed Oct 17, 2023
1 parent 2fe6eef commit b7f7c13
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 7 deletions.
7 changes: 4 additions & 3 deletions app/models/establishment_user_role.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ class EstablishmentUserRole < ApplicationRecord

enum role: { dir: 0, authorised: 1 }

validates :role,
presence: true,
uniqueness: { scope: %i[establishment_id user_id] }
validates :role, presence: true

validates :user,
uniqueness: { scope: %i[establishment_id] }
end
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

class AddUniqueIndexOnEstablishmentUsers < ActiveRecord::Migration[7.1]
def change
add_index :establishment_users, %i[establishment_id user_id role], unique: true
add_index :establishment_users, %i[establishment_id user_id], unique: true
end
end
2 changes: 1 addition & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions spec/models/establishment_user_role_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
# outside of one-line blocks, but if this was to be a one-liner then
# the line would be too long... tough times.
is_expected.to( # rubocop:disable RSpec/ImplicitSubject
validate_uniqueness_of(:role)
.scoped_to(:establishment_id, :user_id)
validate_uniqueness_of(:user)
.scoped_to(:establishment_id)
.ignoring_case_sensitivity
)
}
Expand Down

0 comments on commit b7f7c13

Please sign in to comment.