Try to fix wrong try usage

`Object#try` checks "whether receiver is nil or not". It doesn't rescue
any exceptions raised in method call.

    > User.new(name: "admin", password_digest: "invalid-hash").authenticate("X")
    BCrypt::Errors::InvalidHash: invalid hash
            from /var/lib/gems/2.1.0/gems/bcrypt-3.1.7/lib/bcrypt/password.rb:60:in `initialize'
            ...
This commit is contained in:
Kouhei Sutou 2014-08-19 21:21:35 +09:00
parent ba31ef566a
commit ab903716bc
2 changed files with 7 additions and 2 deletions

View File

@ -16,8 +16,7 @@ class ApplicationController < ActionController::Base
def current_user
return unless session[:succeed_password]
# NOTE: if hashed password is invalid or broken, .authenticate would raise error. Using `try` is avoid that situation
@current_user ||= User.new(name: "admin").try(:authenticate, session[:succeed_password])
@current_user ||= User.new(name: "admin").authenticate(session[:succeed_password])
end
def login_required

View File

@ -19,6 +19,12 @@ class User
validates :password, length: { minimum: 8 }
validate :valid_current_password
def authenticate(unencrypted_password)
super
rescue BCrypt::Errors::InvalidHash
false
end
def password_digest
@password_digest ||
begin