Hi,
I've enjoyed reading your article and applying the code to side project of mine. Thanks for writting this down for others to learn.
I've noticed that with Rails 7 native DB encryption feature, we can simplify the token encryption.
We need to generate the keys with $ bin/rails db:encryption:init
and store the resul in the cedentials with $ bin/rails credentials:edit
.
The migration must be changed to :
class CreateApiKeys < ActiveRecord::Migration[7.0]
def up
create_table :api_keys do |t|
t.string :token
t.references :bearer, polymorphic: true, null: false
end
add_index :api_keys, [:bearer_id, :bearer_type]
add_index :api_keys, :token, unique: true
end
def down
drop_table :api_keys
end
end
and the ApiKey
model can be reduced to this :
class ApiKey < ApplicationRecord
encrypts :token, deterministic: true
belongs_to :bearer, polymorphic: true
def self.authenticate_by_token!(token)
find_by! token: token
end
def self.authenticate_by_token(token)
authenticate_by_token! token
rescue ActiveRecord::RecordNotFound
nil
end
end
There is nothing to deal with for storing the HMAC key, no manual digest storage, cleaning, swapping…