ruby - Rails minitest BCrypt::Errors::InvalidHash:

标签 ruby ruby-on-rails-4 minitest bcrypt digest

我一直在关注 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/

相关文章:

ruby-on-rails - Learn Enough Setup 的 Ruby 安装失败 - Puma gem 安装错误,Mac Sierra

ruby - 如何说服 Rubygems (1.3.3) 我确实希望它安装依赖项?

ruby-on-rails - 有没有更好的衬垫来处理 "unless somthing.nil? || something[:key].nil?"

ruby-on-rails - 具有嵌套命名空间的 Rails 4 引擎

ruby - 最小测试规范 : multiple before/end blocks

ruby-on-rails - 规范样式语法与 minitest in rails

ruby : "if !object.nil?"或 "if object"

ruby-on-rails - Rails 生成 Controller 给我加载错误

ruby-on-rails - Rspec 测试 API 版本控制

ruby-on-rails - 如何在 Rails 中使用具有外键约束的数据库中的测试和装置?