Rails Devise認証のカスタマイズメモ



Deviseのデフォルトの認証ではDBに保存されているemail, passwordの項目で認証を行なっている。
例えば、DBにemail, passwordを別で認証する場合、カスタマイズが必要となる。
そのカスタマイズ方法を調査した内容を以下に記す。

※omniauthを使った外部サイトで認証・callbackではないです。

バージョン情報
 Rails 3.2.6
 Devise 2.1.2


 ・usersテーブルにログインユーザの情報を保持。
 ・パスワードはDBに保持していない。(ここでは 'password' 固定)

1.認証処理の追加

 Deviseでは認証処理はstrategyとして作成されている。
 認証方法をカスタマイズするにはstrategyを新たに作成する。


※以下の内容はDeviseのstrategy(database_authenticatable)を参考に、パスワード判定のみ変 更。
・config/initializers/devise_strategies.rb
require 'devise/strategies/authenticatable'
module Devise
module Strategies
class CustomAuthenticatable < Authenticatable
def authenticate!
resource = valid_password? && mapping.to.find_for_database_authentication(authentication_hash)
return fail(:invalid) unless resource
if validate(resource){ password == 'password' }
resource.after_database_authentication success!(resource)

end
end
end

end
end
Warden::Strategies.add(:custom_authenticatable, Devise::Strategies::CustomAuthenticatable)


2.追加したstrategyを使用するように設定
 追加したstrategyを使用するようにDeviseの設定を行う。
 →database_authenticatableをcustom_authenticatableに置き換える


・config/initializers/devise.rb
Devise.setup do |config|




config.warden do |manager|
customer_strategies = manager.default_strategies(:scope => :user)

customer_strategies.each_index do |i|
customer_strategies[i] = :custom_authenticatable if customer_strategies[i] == :database_authenticatable

end
end
end


以上

コメント

このブログの人気の投稿

AMD環境でKVM PCIパススルー (PT2で)

NagiosとSlackの連携時、Channelを指定する