websocket-rails/websocket-rails — pull request #217 by phlegx (2014-05-05 13:16:10+00:00)
Title: Solves Warden compatibility and gives the possibility to register an user after connection established.

* **Solves #216: current_user is not compatible with Warden (Devise):** Warden makes available an object ```"current_#{class}"``` after successful sign in. The name of the object depends on the model given as authenticable object. Websocket-rails has ```current_user``` hardcoded.
* **Possibility to register an user after connection established.** Two methods are added on ```connection```: ```register_user``` and ```destroy_user```. With this two methods its now possible to register (associate a user to a connection) the current entity (e.g. current_user) after the connection is established (useful in case if you have a non-browser websocket client (c++, java,...) and you want to make the authentication over websocket).

**Example using Rails 4, Devise 3.2.4, Websocket-Rails:**

* The authenticable model object
```ruby
# app/models/account.rb
class Account < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

before_save :ensure_authentication_token

def ensure_authentication_token
if authentication_token.blank?
self.authentication_token = generate_authentication_token
end
end

private

def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless Account.where(authentication_token: token).first
end
end
...
end
```

* The websocket-rails configuration
```ruby
# config/initializers/websocket_rails.rb
WebsocketRails.setup do |config|
config.user_identifier = :id
config.user_class = Account
...
end
```

* The websocket-rails controller
```ruby
class WebsocketController < WebsocketRails::BaseController
before_filter :authenticate_account_from_token!
before_filter :authenticate_account!

def authenticate_account_from_token!
unless account_signed_in?
account_email = message[:auth][:id].presence
account = account_email && Account.find_by_email(account_email)
if account && Devise.secure_compare(account.authentication_token, message[:auth][:token])
sign_in account, store: false
connection.register_user
end
end
end
```