2017-10-11 223 views
2

我使用ActionCable開發Ruby on Rails 5.1應用程序。 User authentification via Devise適用於多個渠道。現在,我想添加一個第二種類型的頻道,它不需要任何用戶認證。更確切地說,我想讓匿名網站訪問者與支持人員聊天。使用ActionCable和多種識別方法

我目前通過驗證的用戶執行的ApplicationCable::Connection看起來是這樣的:

# app/channels/application_cable/connection.rb 

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_by(id: cookies.signed['user.id']) 
     return user if user 
     fail 'User needs to be authenticated.' 
    end 
    end 
end 

匿名用戶將通過一些隨機UUID(SecureRandom.urlsafe_base64)標識。

問:

如何最好添加這種新型渠道?我可以在某處添加一個布爾標誌require_authentification,在繼承的通道類中爲匿名通信覆蓋它,並根據此屬性切換Connection中的標識方法?或者我寧願實施一個全新的模塊,比如AnonymousApplicationCable

+0

看一看Guest用戶創建...... [由設計維基解釋(https://github.com/plataformatec/devise/wiki /操作方法:創建客戶用戶) – Myst

+0

感謝您的反饋,@Myst,不幸的是,我無法爲每個單個websocket連接創建(訪客)用戶......我需要暫時識別通過UUID連接,無需使用Devise – Boris

+0

@Boris您是否找到任何解決方案?我需要這個爲我的電子應用 – Osmond

回答

0

嗨我進入了同樣的問題,在rails github評論中查看您的解決方案後,我認爲創建令牌並將邏輯保存在connect方法中會更好。

所以我所做的只是通過檢查監督員,如果不是,只是創建匿名標記,否則。對於這項工作,我需要聲明2標識符:uuid和:CURRENT_USER

class Connection < ActionCable::Connection::Base 
identified_by :current_user, :uuid 


def connect 

    if !env['warden'].user 
    self.uuid = SecureRandom.urlsafe_base64 
    else 
    self.current_user = find_verified_user 
    end 

end 

protected 

def find_verified_user # this checks whether a user is authenticated with devise 

    if verified_user = env['warden'].user 

    verified_user 
    else 

    reject_unauthorized_connection 
    end 
end 

end