我試圖做一個自定義身份驗證,以更好地瞭解發生了什麼事情。過了好一會兒讓它接受密碼和password_confirmation,但現在它只是不會工作,我所有的想法身份驗證沒有has_secure_password
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+\-.][email protected][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.save
或verify_password_confirmation
和重新渲染
什麼是錯誤/哪個部分不工作? – omarshammas
同樣,在verify_password方法中,您應該比較self.password_digest == BCrypt :: Password.new(密碼) – omarshammas
不要執行自定義認證,您會做錯誤的。例如,如果你想學習閱讀Devise gem的代碼。 –