Skip to content

Commit

Permalink
Ensure that api keys are unique
Browse files Browse the repository at this point in the history
  • Loading branch information
mlandauer committed Aug 8, 2024
1 parent 968ffe4 commit 5678646
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
6 changes: 3 additions & 3 deletions app/models/api_key.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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|
Expand Down

0 comments on commit 5678646

Please sign in to comment.