deviseでログイン必須ページ、リダイレクトページ指定


railsのdeviseでは、閲覧やアクションのためにログイン必須なページを作ることができます。
また、未ログイン状態でログイン必須ページにアクセスした場合、自動的にsign_in_pathに飛ばされます。
このredirect先が都合が悪い場合の変更方法。(OAuth認証のみにした場合、都合が悪くなりました)

deviseの導入や環境は前回の記事を参照してください。
「deviseでfacebook,twitter認証」 http://goo.gl/0Mnl4

1. ログイン必須なページを作る

Controller側で、以下のように設定してください。

app/controllers/hoge_controller.rb
 before_filter :authenticate_user!, :except=>[:hello]
  def hello
    .
    .
    .
  end
.
.
.

この場合、hello action以外はログイン必須となります。ログイン不要なアクションは、[:hello,:bye]のように複数指定も可能です。

2. リダイレクト先指定

ログイン必須ページにゲストで入った場合のリダイレクト先を変更します。

2-1. devise設定

devise.rbの一番下にある # config.warden do |manager| をコメントインし、以下に変更。

config/initializer/devise.rb
  config.warden do |manager|
     manager.failure_app = CustomAuthenticationFailure
  #   manager.intercept_401 = false
  #   manager.default_strategies(:scope => :user).unshift :some_external_strategy
   end

2-2. リダイレクト先の指定

ライブラリーに以下のファイルを作成します。
前回の記事の続きで、自動でfacebook認証させることもできます。

lib/custom_authentication_failure.rb
  class CustomAuthenticationFailure < Devise::FailureApp 
  protected 
    def redirect_url 
      root_path #rootに飛ばす場合
  #    root_path+"users/auth/facebook" #自動でfacebook認証させる場合
    end 
  end 

2-3. ライブラリーを読みこませる

configに以下の行を追記します。似たような行がコメントアウトされてるので、その下にでも。

config/application.rb
.
.
    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)
      config.autoload_paths += %W(#{config.root}/lib)
.
.

これでサーバーを立ち上げ直し、ログイン必須ページに飛んだときにリダイレクトされていれば成功です。