diff --git a/app/models/api_key.rb b/app/models/api_key.rb index 87b24af11..c4bd06ea4 100644 --- a/app/models/api_key.rb +++ b/app/models/api_key.rb @@ -7,10 +7,9 @@ class ApiKey < ApplicationRecord belongs_to :user has_many :daily_api_usages, dependent: :destroy - before_create :set_value + validates :value, uniqueness: true - # TODO: Ensure that value is unique - # There should be a validation here and a unique index in the schema + before_create :set_value sig { params(value: String).returns(T.nilable(ApiKey)) } def self.find_valid(value) @@ -33,6 +32,7 @@ def self.daily_limit_with_default(value) private + # TODO: Retry if api key value is not unique sig { void } def set_value self.value = SecureRandom.base58(20) diff --git a/db/migrate/20240808005105_add_unique_index_to_api_key_value.rb b/db/migrate/20240808005105_add_unique_index_to_api_key_value.rb new file mode 100644 index 000000000..b5eaff1a7 --- /dev/null +++ b/db/migrate/20240808005105_add_unique_index_to_api_key_value.rb @@ -0,0 +1,7 @@ +class AddUniqueIndexToApiKeyValue < ActiveRecord::Migration[7.1] + def change + # Recreate the index and make it unique + remove_index :api_keys, :value + add_index :api_keys, :value, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 636083f4e..c2b6d931a 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[7.1].define(version: 2024_07_31_043561) do +ActiveRecord::Schema[7.1].define(version: 2024_08_08_005105) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" enable_extension "postgis" @@ -97,7 +97,7 @@ t.datetime "created_at", precision: nil, null: false t.datetime "updated_at", precision: nil, null: false t.index ["user_id"], name: "index_api_keys_on_user_id" - t.index ["value"], name: "index_api_keys_on_value" + t.index ["value"], name: "index_api_keys_on_value", unique: true end create_table "application_redirects", id: :serial, force: :cascade do |t|