なんとなく日々徒然と

Deviseちょっとしたtips2つ

Deviseの小技2つです。

1. deviseでログインに失敗した際にアクセスされたページを元に任意のページへ飛ばす。

1
2
3
4
5
6
# config/initializers/devise.rb
Devise.setup do |config|
  config.warden do |manager|
    manager.failure_app = CustomAuthenticationFailure
  end
end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# lib/custom_authentication_failure.rb
class CustomAuthenticationFailure < Devise::FailureApp
  protected

  def redirect_url
    uri = URI.parse(warden_options[:attempted_path])
    if uri.path.start_with?('/admin')
      hogehoge_url # adminではじまる場合に飛ばしたいurl
    else
      super # それ以外の場合は通常のdeviseの処理へ流す
    end
  end
end

warden_options[:attempted_path]でアクセスしようとしたパスが参照できます

2. ログインエリアのurlにアクセスした時に保存するurlを操作

deviseはデフォルトでログインエリアにアクセスした際に未ログイン状態だとそのアクセスしたパスをsessionに保存してくれ、
ログイン後にそのurlにリダイレクトしてくれる機能があります。

特定のurlを覚えさせたくなかったのでパッチをあてました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# config/initializers/devise.rb
module StoreLocationPatch
  def store_location_for(resource_or_scope, location)
    return if URI.parse(location).path == '/' # rootへのアクセスは記憶させない
    super
  end
end

module Devise
  module Controllers
    module StoreLocation
      prepend StoreLocationPatch
    end
  end
end

Tags:

平塚新港 稚鮎 小サバ フグ 梅雨用に防水の釣りシューズを買ったよ

comments powered by Disqus