2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[devise][sorcery]ActionCable内でcurrent_userを使えるようにする方法

Posted at

簡単に認証機能を実装できるdevise, sorceryそれぞれのcurrent_userメソッドをActionCableにて使えるようにする方法を記載します。

前提

1:1のチャット機能を想定しております。

ActionCableの導入や説明などは割愛させて頂きます。

それぞれapp/channels/application_cable/connection.rbに記述していきます。

devise

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

    def connect
      reject_unauthorized_connection unless find_verified_user
    end

    private

      def find_verified_user
        self.current_user = env['warden'].user
      end
  end
end

identified_by...クライアントとサーバーとの関係を成立させる基礎であるコネクションを識別するためのキー

sorcery

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

    def connect
      self.current_user = find_verfied_user
    end

    protected

    def find_verfied_user
      if current_user = User.find_by_id(request.session[:user_id])
        current_user
      else
        reject_unauthorized_connection
      end
    end
  end
end
2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?