diff --git a/app/models/api_key.rb b/app/models/api_key.rb index aca02f54d..a08998db9 100644 --- a/app/models/api_key.rb +++ b/app/models/api_key.rb @@ -2,12 +2,14 @@ class ApiKey < ApplicationRecord belongs_to :user validates_uniqueness_of :user_id validates_uniqueness_of :key + has_secure_token :key def self.generate!(user) - create(:user_id => user.id, :key => SecureRandom.urlsafe_base64(32)) + create(:user_id => user.id) end def regenerate! - update!(:key => SecureRandom.urlsafe_base64(32)) + regenerate_key + save end end diff --git a/app/models/user_password_reset_nonce.rb b/app/models/user_password_reset_nonce.rb index 012720a2d..d1324969a 100644 --- a/app/models/user_password_reset_nonce.rb +++ b/app/models/user_password_reset_nonce.rb @@ -1,7 +1,7 @@ class UserPasswordResetNonce < ApplicationRecord - validates_presence_of :email, :key + has_secure_token :key + validates_presence_of :email validate :validate_existence_of_email - before_validation :initialize_key, :on => :create after_create :deliver_notice def self.prune! @@ -12,10 +12,6 @@ class UserPasswordResetNonce < ApplicationRecord Maintenance::User::PasswordResetMailer.reset_request(user, self).deliver_now end - def initialize_key - self.key = SecureRandom.hex(16) - end - def validate_existence_of_email if !User.with_email(email).exists? errors[:email] << "is invalid" diff --git a/test/unit/api_key_test.rb b/test/unit/api_key_test.rb index 51b6b5524..09812dfd2 100644 --- a/test/unit/api_key_test.rb +++ b/test/unit/api_key_test.rb @@ -7,6 +7,16 @@ class ApiKeyTest < ActiveSupport::TestCase @api_key = ApiKey.generate!(@user) end + should "regenerate the key" do + assert_changes(-> { @api_key.key }) do + @api_key.regenerate! + end + end + + should "generate a unique key" do + assert_not_nil(@api_key.key) + end + should "authenticate via api key" do assert_not_nil(User.authenticate_api_key(@user.name, @api_key.key)) end diff --git a/test/unit/user_password_reset_nonce_test.rb b/test/unit/user_password_reset_nonce_test.rb index 1aae392c9..a794fc1fa 100644 --- a/test/unit/user_password_reset_nonce_test.rb +++ b/test/unit/user_password_reset_nonce_test.rb @@ -13,7 +13,7 @@ class UserPasswordResetNonceTest < ActiveSupport::TestCase end should "populate the key with a random string" do - assert_equal(32, @nonce.key.size) + assert_equal(24, @nonce.key.size) end should "reset the password when reset" do