adamniedzielski/tiddle

[Question] Cookieless Tiddle & ActionCable

Closed this issue · 2 comments

I've been looking in the documentation and have not found a way to do "manual" authentication to authenticate a websocket connection. Is there any way to do this without using cookies?

The topic of authentication in Websockets connections is completely foreign to me. Sadly I can't offer any guidance here.

For anyone else who comes across this and is looking for the same thing. Here is how I got Tiddle working in ActionCable.
@adamniedzielski might be worth adding to the documentation.

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 = User.find_for_authentication(email: request.params[:user_email])
      reject_unauthorized_connection unless user

      token = Tiddle::TokenIssuer.build.find_token(user, request.params[:user_token])
      if token && unexpired?(token)
        return user
      end

      reject_unauthorized_connection
    end

    def unexpired?(token)
      return true unless token.respond_to?(:expires_in)
      return true if token.expires_in.blank? || token.expires_in.zero?

      Time.current <= token.last_used_at + token.expires_in
    end
  end
end

This isn't a perfect solution and I don't really like sending tokens via query params, but it works. Note that it makes a few assumptions and hard codes variable names (model is User, key is email and sent via a query param of user_email and token is sent via query param of user_token)