我一直在关注 Hartl 的 Rails 教程,并且正在对我的登录实现迷你测试。目前,一切正常,用户可以成功登录。
但是当我在我的登录集成上运行测试时,我在尝试消化 token 时不断收到此错误....
BCrypt::Errors::InvalidHash: invalid hash
app/controllers/sessions_controller.rb:13:in `create'
test/integration/users_login_test.rb:21:in `block in <class:UsersLoginTest>'
app/controllers/sessions_controller.rb:13:in `create'
test/integration/users_login_test.rb:21:in `block in <class:UsersLoginTest>'
谁能帮我理解这个错误以及我该如何解决它。
型号
class User < ActiveRecord::Base
belongs_to :district
belongs_to :school
###Why doesn't this work?------
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
end
装置 (users.yml)
tom:
district_id: 1
school_id: 6
firstName: Tommy
lastName: Pickles
username: pickleman
email: pickleman@gmail.com
###Error on this line------
password_digest: <%= User.digest('password') %>
整合(user_login_test.rb)
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:tom)
end
test "login with valid information" do
get login_path
###Error on Sign Up Here------
post sessions_path, session: { username: @user.username, password: 'password' }
assert_redirected_to district_district_resources_path(@user.district)
follow_redirect!
assert_template 'sessions/new'
assert_select "a[href=?]", login_path, count: 0
end
end
Controller
class SessionsController < ApplicationController
#create session for login
def create
user = User.find_by(username: params[:session][:username]) if defined? params[:session][:username]
district = user.district if user
school = user.school if user
if user && user.authenticate(params[:session][:password]) && district
user_sign_in user
redirect_to district_district_resources_path(district)
else
flash.now[:error] = 'Invalid username / password combination' # Not quite right!
render 'new'
end
end
最佳答案
BCrypt::Errors::InvalidHash
当存储在 password_digest
中的散列不是有效的 BCrypt 散列时引发。
简而言之,您不能只在其中转储任何 SHA1,您需要像这样创建一个散列:
sha1_password = Digest::SHA1.hexdigest(token.to_s)
BCrypt::Password.create(sha1_password).to_s
参见 this answer有关此主题的详细解释。
关于ruby - Rails minitest BCrypt::Errors::InvalidHash:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507250/