diff --git a/db/migrate/20210630165919_add_index_to_organization_users.rb b/db/migrate/20210630165919_add_index_to_organization_users.rb new file mode 100644 index 0000000000..357b154ac3 --- /dev/null +++ b/db/migrate/20210630165919_add_index_to_organization_users.rb @@ -0,0 +1,5 @@ +class AddIndexToOrganizationUsers < ActiveRecord::Migration[6.1] + def change + add_index :organization_users, [:organization_id, :user_id], unique: true, if_not_exists: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 5ffd80a70d..28b0030bb7 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2021_06_19_124759) do +ActiveRecord::Schema.define(version: 2021_06_30_165919) do # These are extensions that must be enabled in order to support this database enable_extension "pgcrypto" @@ -142,6 +142,7 @@ ActiveRecord::Schema.define(version: 2021_06_19_124759) do t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "status", default: "invited" + t.index ["organization_id", "user_id"], name: "index_organization_users_on_organization_id_and_user_id", unique: true t.index ["organization_id"], name: "index_organization_users_on_organization_id" t.index ["user_id"], name: "index_organization_users_on_user_id" end diff --git a/test/controllers/organization_users_controller_test.rb b/test/controllers/organization_users_controller_test.rb index b51a5677e9..503814c73c 100644 --- a/test/controllers/organization_users_controller_test.rb +++ b/test/controllers/organization_users_controller_test.rb @@ -28,6 +28,21 @@ class OrganizationUsersControllerTest < ActionDispatch::IntegrationTest end end + test 'org admins cannot create org users if email already exists' do + post '/organization_users', params: org_user_params, as: :json, headers: auth_header(@admin) + post '/organization_users', params: org_user_params, as: :json, headers: auth_header(@admin) + + assert_response 422 + assert_equal "Email address is already taken", JSON.parse(response.body)['message'] + end + + test 'OrganizationUser should be unique per organization and user' do + assert_raises(ActiveRecord::RecordNotUnique) do + org_user = OrganizationUser.new(organization: @org, user: @admin, role: 'admin', status: 'active') + org_user.save + end + end + test 'cannot create org users if not admin' do assert_no_difference 'OrganizationUser.count' do post '/organization_users', params: org_user_params, as: :json, headers: auth_header(@developer)