Rails 密码保存方法
密码保存原则:加salt并hash后保存,杜绝明文存储
Rails 3.1以前
#model代码 require 'digest/sha2' class User < ActiveRecord::Base #attr_accessible限制只能更新部分字段 attr_accessible :email, :password, :password_confirmation before_save :encrypt_password attr_accessor :password #validates_confirmation_of会自动添加password_confirmation并验证确认密码 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 == Digest::SHA2.hexdigest(password + user.password_salt) user else nil end end private def encrypt_password self.password_salt = self.object_id.to_s + rand.to_s self.password_hash = Digest::SHA2.hexdigest(password + password_salt) end end
使用has_secure_password
Rails 3.1开始新加了
has_secure_password,参见这篇:Rails 3.1中Authentication验证
Rails 3.1后(不包括Rails 3.1)为了避免整个Rails强引用bcrypt-ruby库,需要时has_secure_password时要手动在Gemfile中引入
gem 'bcrypt-ruby'
利用第三方gem
omniauth 这个很活跃,非常推荐 https://github.com/intridea/omniauth