LoginSignup
40
34

More than 5 years have passed since last update.

ActionCableでDeviseのcurrent_userを扱う

Posted at

【注意!】この記事はRails 5.0.0RC1を対象にしています。他のバージョンでの挙動は分かりません。あとそのうちDevise側が対応してくると思います。 (3.5では未対応)

Rails 5の目玉機能といえば、ActiveCable。実際に使うとなるとDeviseなどの認証機構と一緒に使うと思います。

しかし、ActionCable + Deviseをググってもあまり良い情報は出てこず、ログインしたらcookieにcurrent_user.idを書くと良いよという記事が真っ先に出てきます。

そんな雑な方法はイヤなので、sessionから読むようにしてみます。

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    protected
    def find_verified_user
      User.find(session['warden.user.user.key'][0][0])
    rescue
      reject_unauthorized_connection
    end

    def session
      @session ||= cookies.encrypted[Rails.application.config.session_options[:key]]
    end
  end
end

モデル名がAccountの場合セッションキーはwarden.user.account.keyだと思います。これ、ベタ書きでかっこ悪いのでちゃんと取得する方法があったら誰かコメントで教えてください。よろしくお願いします。

p.s
今のところ、Deviseの公式GemはRails 5に対応していないのでdevelopブランチを使ってください。

gem 'devise', git: 'https://github.com/plataformatec/devise.git'
40
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
34