title: Receiving An unauthorized connection attempt was rejected w/ActionCable checking for Null Users
body: <p>I'm trying to stop ActionCable from continuously checking for users that are not logged into the server. I deleted all users in my test environment to check if this issue would persist, but it shows no sign of ending, even after I added a conditional statement to the JS file to check for the current_user's id. How can I finally bring an end to ActionCable attempting to connect users that don't exist or aren't logged in? Btw, I'm using JQuery3 and Rails 5.</p>
  
  <p>Console Log</p>
  
  <pre><code>Started GET "/cable" for 127.0.0.1 at 2018-02-27 00:11:41 -0500
     (1.0ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2018-02-27 00:11:42 -0500
  Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
    User Load (2.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT $1  [["LIMIT", 1]]
  An unauthorized connection attempt was rejected
  Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
  Finished "/cable/" [WebSocket] for 127.0.0.1 at 2018-02-27 00:11:42 -0500
  Finished "/cable/" [WebSocket] for 127.0.0.1 at 2018-02-27 00:11:42 -0500
  Started GET "/cable" for 127.0.0.1 at 2018-02-27 00:12:09 -0500
  </code></pre>
  
  <p>connection.rb</p>
  
  <pre><code>module ApplicationCable
    class Connection &lt; ActionCable::Connection::Base
      identified_by :current_user
  
      def connect
        self.current_user = find_verified_user
        logger.add_tags 'ActionCable', current_user.username
      end
  
      protected
      def find_verified_user
        verified_user = User.find_by(id: cookies.signed['user.id'])
        if verified_user &amp;&amp; cookies.signed['user.expires_at'] &gt; Time.now
          verified_user
        else
          reject_unauthorized_connection
        end
      end
    end
  end
  </code></pre>
  
  <p>cable.js</p>
  
  <pre><code>// Action Cable provides the framework to deal with WebSockets in Rails.
  // You can generate new channels where WebSocket features live using the `rails generate channel` command.
  //
  //= require action_cable
  //= require_self
  //= require_tree ./channels
  
  (function() {
    this.App || (this.App = {});
  
    App.cable = ActionCable.createConsumer();
  
  }).call(this);
  </code></pre>
  
  <p>chatroom.js</p>
  
  <pre><code>$(document).on('turbolinks:load', function () {
      if ($("meta[name='current-user']").length &gt; 0) {
          (function () {
              App.chatrooms = App.cable.subscriptions.create("ChatroomsChannel", {
                  connected: function () {
                  },
                  disconnected: function () {
                  },
                  received: function (data) {
                      var active_chatroom;
                      active_chatroom = $("[data-behavior='messages'][data-chatroom-id='" + data.chatroom_id + "']");
                      if (active_chatroom.length &gt; 0) {
                          if (document.hidden) {
                              if ($(".strike").length === 0) {
                                  active_chatroom.append("&lt;div class='strike'&gt;&lt;span&gt;Unread Messages&lt;/span&gt;&lt;/div&gt;");
                              }
                              if (Notification.permission === "granted") {
                                  new Notification(data.username, {
                                      body: data.body
                                  });
                              }
                          } else {
                              App.last_read.update(data.chatroom_id);
                          }
                          return active_chatroom.append("&lt;div class='media message'&gt; &lt;div class='media-body'&gt; &lt;h5 class='mt-0 message-username-pos'&gt;" + data.username + "&lt;/h5&gt; &lt;p&gt;" + data.body + "&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;");
                      } else {
                          return $("[data-behavior='chatroom-link'][data-chatroom-id='" + data.chatroom_id + "']").css("font-weight", "bold");
                      }
                  },
                  send_message: function (chatroom_id, message) {
                      return this.perform("send_message", {
                          chatroom_id: chatroom_id,
                          body: message
                      });
                  }
              });
  
          }).call(this);
      }
  });
  </code></pre>
  
  <p>last_read.js</p>
  
  <pre><code>$(document).on('turbolinks:load', function () {
      if ($("meta[name='current-user']").length &gt; 0) {
          (function () {
              App.last_read = App.cable.subscriptions.create("LastReadChannel", {
                  connected: function () {
                  },
                  disconnected: function () {
                  },
                  received: function (data) {
                  },
                  update: function (chatroom_id) {
                      return this.perform("update", {
                          chatroom_id: chatroom_id
                      });
                  }
              });
  
          }).call(this);
      }
  });
  </code></pre>
  
  <p>application.html.erb</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  
    &lt;title&gt;Test App&lt;/title&gt;
    &lt;%= csrf_meta_tags %&gt;
  
    &lt;%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %&gt;
    &lt;%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %&gt;
    &lt;%= javascript_include_tag 'https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js' %&gt;
    &lt;%= javascript_include_tag 'https://js.stripe.com/v3/' %&gt;
    &lt;%= favicon_link_tag 'favicon.ico' %&gt;
    &lt;% if user_signed_in? %&gt;
        &lt;%= tag :meta, name: 'current-user', data: {id: current_user.id} %&gt;
    &lt;% end %&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>warden_hooks.rb</p>
  
  <pre><code>Warden::Manager.after_set_user do |user,auth,opts|
    scope = opts[:scope]
    auth.cookies.signed["#{scope}.id"] = user.id
    auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now
  end
  
  Warden::Manager.before_logout do |user, auth, opts|
    scope = opts[:scope]
    auth.cookies.signed["#{scope}.id"] = nil
    auth.cookies.signed["#{scope}.expires_at"] = nil
  end
  </code></pre>