没有has_secure_password的身份验证

时间:2013-06-19 21:58:05

标签: ruby-on-rails authentication

我正在尝试进行自定义身份验证,以便更好地了解幕后发生了什么。它需要一段时间才能让它接受密码和password_confirmation,但现在它不会工作,我完全没有想法

class UsersController < ApplicationController
def new
    @user = User.new
  end

  def create
    par = params[:user]
    @user = User.new(params[:user])
    if @user.verify_password_confirmation(par[:password], par[:password_confirmation]) && @user.save
      sign_in @user
      redirect_to user_url(@user)
    else
      render 'new'
    end
  end
end

在attr_accessor中有密码和password_confirmation是否有任何危险?

require 'bcrypt'

class User < ActiveRecord::Base
  attr_accessor :password_confirmation, :password
  attr_accessible :name, :email, :password, :password_confirmation

  before_save { email.downcase! }

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d]\-.]+\.[a-z]+\z/i
  validates :email, presence: true,
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  validates :password, length: { minimum: 6 }

  validates :password_confirmation, presence: true

  def password=(password)
    self.password_digest = BCrypt::Password.create(password)
  end

  def verify_password(password) #for the sessions, which obviously I can't check yet
    BCrypt::Password.new(self.password_digest) == password
  end

  def verify_password_confirmation(pass, pass_con) #couldn't see how else to confirm it
    pass_con == pass
  end

  def reset_session_token!
    self.session_token = SecureRandom::base64(32)
    self.save!

    self.session_token
  end
end

编辑:具体问题是它在@user.saveverify_password_confirmation失败并重新渲染

1 个答案:

答案 0 :(得分:0)

在github上查看secure_password.rb。 has_secure_password比其他第三方认证宝石或插件更简单,清晰且易于理解。 另请注意,has_secure_password使用bcrypt-ruby gem生成password_digest。因此,如果您想要推出自己的身份验证系统,那么您也需要考虑其安全性。