Railsでユーザー認証
こんばんわ。
bcrypt-ruby使ってユーザー認証を実装してみました
// パスワードハッシュ化の比較を見る限り、メンテナンスの問題でOpenSSL系推奨でしたが
// デフォルトでGemfileに記述されているって理由でbcrypt-rubyを選択しました。
// 危険そうだったら変えるかも。
$ vim /Gemfile gem 'bcrypt-ruby' :wq $ bundle install
User Modelを作る
rails g model user user_id:string password_digest:string
/app/model/user.rbを少し変える
class User < ActiveRecord::Base has_secure_password attr_accessible :user_id, :password_digest, :password, :password_confirmation end
/app/controller/signup_controller.rbをそれっぽくする
class SignupController < ApplicationController def index end def post @user_id = params[:user_id] @password = params[:password] @password_confirmation = params[:password_confirmation] case when @user_id == nil # user_idが入力されてない @message = 'User ID required to sign up.' when @password == nil # passwordが入力されてない @message = 'PASSWORD required to sign up.' when @password != @password_confirmation # passwordが一致してない @message = 'The passwords do not match.' when User.where(:user_id => @user_id).count > 0 # user_idが既に使われている @message = 'This User ID already in use.' else @user = User.new({ :user_id => @user_id, :password => @password, :password_confirmation => @password_confirmation, }) if @user.save then # 登録に成功した @message = 'success' else # 登録に失敗した @message = 'DB error' end end render 'index' end end
これだけでpassword_digestにパスワードがハッシュ化されて登録された!
ちなみにログインはLoginコントローラーをジェネレートして
こんな感じのことすればOK
@user = User.find_by_user_id @user_id case when !@user @message = 'Incorrect User ID.' when !@user.authenticate(@password) @message = 'Incorrect PASSWORD.' else @message = 'SUCCESS!' end
とっても簡単だー
多重ログインできない仕組みについて次回は書きたいところ。
参考
http://bcrypt-ruby.rubyforge.org/
おしまい。
追記
あけましておめでとうございます。
今年もよろしくお願いします。