janko / rodauth-rails

Rails integration for Rodauth authentication framework
https://github.com/jeremyevans/rodauth
MIT License
571 stars 40 forks source link

How would you authentication a new connection for ActionCable via the session cookie? #151

Closed kyle-rader closed 1 year ago

kyle-rader commented 1 year ago

I'm starting to use ActionCable and have a connection class that looks like the following. What's the best way to authenticate this connection using the existing session?

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

    def connect
      self.current_user = find_verified_user
    end

    private

    def find_verified_user
      # Question: How to find current user from session?
      if verified_user = Account.find_by(id: cookies.encrypted[??]) # or Some Rodauth::Auth::auth_method?
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end
janko commented 1 year ago

If Action Cable connections have access to request env, you should be able to do:

verified_user = env["rodauth"].rails_account

For secondary configurations, e.g. :admin, you'd call env["rodauth.admin"].

It might be worth adding similar helpers for controllers to Action Cable connections in rodauth-rails 🤔

janko commented 1 year ago

I'm going to close this, as it's not a bug report. Please ask usage questions in discussions channel 🙂