From 5ef40133dd7e6917f27f90859fcb2aaa57ca438a Mon Sep 17 00:00:00 2001 From: David Roetzel Date: Wed, 26 Jan 2022 14:41:09 +0100 Subject: [PATCH] Allow empty passwords Users with empty password will _not_ be authenticated. This allows the user model to be reused by other authentication schemes that do not rely on a (locally stored) password. --- app/models/user.rb | 10 ++++++++-- test/models/user_test.rb | 17 ++++++++++++++--- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 8f39a43a..c83c58cb 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,11 +1,13 @@ class User < ApplicationRecord - has_secure_password + has_secure_password validations: false before_validation :downcase_email, on: [:create, :update] validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A[^@\s]+@([^@.\s]+\.)+[^@.\s]+\z/ } validates :first_name, :last_name, presence: true - validates :password, length: { minimum: PASSWORD_MIN_LENGTH } + validates :password, length: { minimum: PASSWORD_MIN_LENGTH }, + confirmation: true, + allow_nil: true scope :admins, -> { where(admin: true) } scope :regular, -> { where(admin: false) } @@ -18,6 +20,10 @@ def full_name [first_name, last_name].join(" ") end + def authenticate(given_password) + password_digest.present? && super + end + private def downcase_email diff --git a/test/models/user_test.rb b/test/models/user_test.rb index 82f61e01..fc1a3736 100644 --- a/test/models/user_test.rb +++ b/test/models/user_test.rb @@ -1,7 +1,18 @@ require 'test_helper' class UserTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end + test "#authenticate will not authenticate user without password" do + user = FactoryBot.create(:user, password: nil, password_digest: nil) + refute user.authenticate("secret") + end + + test "#authenticate will authenticate user with correct password" do + user = FactoryBot.create(:user) + assert user.authenticate("secret") + end + + test "#authenticate will not authenticate when given wrong password" do + user = FactoryBot.create(:user) + refute user.authenticate("password") + end end