我是 Rails(以及一般的 ruby)新手,所以我的问题可能很容易解决。我正在尝试创建一个简单的应用程序,您可以在其中创建用户并登录。我正在使用 BCrypt 加密密码,当我尝试登录时,出现此错误:BCrypt::Errors::InvalidSalt in SessionsController#login_attempt
不确定我需要共享哪些文件来解决问题,因此我将首先共享出现错误的文件。
用户.rb
class User < ActiveRecord::Base
before_save :encrypt_password
after_save :clear_password
attr_accessor :password
attr_accessible :username, :email, :password, :password_confirmation
EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true #password_confirmation attr
validates_length_of :password, :in => 6..20, :on => :create
def encrypt_password
if :password.present?
self.salt = BCrypt::Engine.generate_salt
self.encrypted_password= BCrypt::Engine.hash_secret(:password, :salt)
end
end
def clear_password
self.password = nil
end
def self.authenticate(username_or_email="", login_password="")
if EMAIL_REGEX.match(username_or_email)
user = User.find_by_email(username_or_email)
else
user = User.find_by_username(username_or_email)
end
if user && user.match_password(login_password)
return user
else
return false
end
end
def match_password(login_password="")
encrypted_password == BCrypt::Engine.hash_secret(login_password, salt)
end
end
session_controller.rb
class SessionsController < ApplicationController
before_filter :authenticate_user, :only => [:home, :profile, :setting]
before_filter :save_login_state, :only => [:login, :login_attempt]
def login
#Login Form
end
def login_attempt
authorized_user = User.authenticate(params[:username_or_email],params[:login_password])
if authorized_user
flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.username}"
redirect_to(:action => 'home')
else
flash[:notice] = "Invalid Username or Password"
flash[:color]= "invalid"
render "login"
end
end
def home
end
def profile
end
def setting
end
def logout
session[:user_id] = nil
redirect_to :action => 'login'
end
end
我按照教程走到了这一步,所以如果您可以的话,请也解释一下错误。
谢谢!
最佳答案
数据库中不需要有盐字段,使用加密密码就足够了。如果您使用 BCrypt::Password
而不是 BCrypt::Engine
,您可以将 salt 和 enc_pasword 保存在同一字段中。尝试更改 user.rb
def encrypt_password
self.encrypted_password = BCrypt::Password.create(password) if password.present?
end
def match_password(login_password="")
BCrypt::Password.new(password) == login_password
end
关于ruby-on-rails - Ruby on Rails : BCrypt InvalidSalt Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16193166/