【发布时间】:2014-03-30 17:49:11
【问题描述】:
我遵循rails cast tutorial 进行用户身份验证/注册/登录,这显然具有使用 gem 保护属性的过时方法。我发现有必要切换到强参数,并通过关注this method 这样做。
我不得不从我的 user.rb 模型中删除 attr_accessible 代码(在下面注释掉),我想知道除了在控制器中定义用户参数之外,我还应该做些什么。既然我没有 attr_accessible 或者这是不必要的,用户字段(电子邮件、密码、位置)是否应该有 attr_accessors?我是 Rails 新手,不完全了解用户身份验证的正确必要性。
user.rb
class User < ActiveRecord::Base
#attr_accessible :email, :password, :password_confirmation, :location
attr_accessor :password, :location
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
user_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
#add thing from https://stackoverflow.com/a/19130224/2739431
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :location)
end
end
【问题讨论】:
标签: ruby-on-rails ruby strong-parameters authentication