Skip to content

Instantly share code, notes, and snippets.

@tbaba
Created December 22, 2011 14:56
Show Gist options
  • Save tbaba/1510586 to your computer and use it in GitHub Desktop.
Save tbaba/1510586 to your computer and use it in GitHub Desktop.
Rails 3.1 feature: has_secure_password
$ rails console
ruby-1.9.3-p0 :001 > user = User.new
=> #<User id: nil, username: nil, password_digest: nil, created_at: nil, updated_at: nil>
ruby-1.9.3-p0 :002 > user = User.new username: 't.baba', password: 'hogehoge', password_confirmation: 'hogehoge'
=> #<User id: nil, username: "t.baba", password_digest: "$2a$10$HaXYndWU/kgCYopLf5nyb.PnX2QN0BQeKjECuoreZ2qO...", created_at: nil, updated_at: nil>
ruby-1.9.3-p0 :003 > user.save!
Binary data inserted for `string` type on column `password_digest`
=> true
ruby-1.9.3-p0 :005 > user.authenticate 'hoge'
=> false
ruby-1.9.3-p0 :006 > user.authenticate 'hogehoge'
=> #<User id: 2, username: "t.baba", password_digest: "$2a$10$HaXYndWU/kgCYopLf5nyb.PnX2QN0BQeKjECuoreZ2qO...", created_at: "2011-12-22 14:56:11", updated_at: "2011-12-22 14:56:11">
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :password_digest
t.timestamps
end
end
end
user = User.find_by_username params[:username]
if user.authenticate params[:password]
# 成功時の動作
else
# 失敗時の動作
end
class User < ActiveRecord::Base
has_secure_password
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment