This commit is contained in:
Albert Yi
2018-05-15 14:19:45 -07:00
parent c36efc1f62
commit 8bb890e4d0
4 changed files with 17 additions and 9 deletions

View File

@@ -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

View File

@@ -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"

View File

@@ -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

View File

@@ -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