c48f4d9041
- Employee authenticates via auth_token, acts on behalf of a Supplier - Connection now accepts ?supplier_id=ID query param - identified_by :current_supplier_id added - MozoChannel#authorized? allows :employee to subscribe to supplier_<id> when current_supplier_id matches
45 lines
1.6 KiB
Ruby
45 lines
1.6 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
module ApplicationCable
|
|
class Connection < ActionCable::Connection::Base
|
|
# Authenticate via auth_token (same mechanism used in ApplicationController#authenticate_employee!)
|
|
# Clients should pass ?auth_token=TOKEN when connecting to the WebSocket.
|
|
#
|
|
# Auth flows:
|
|
# User app: ?auth_token=<user_token>
|
|
# Supplier app: ?auth_token=<employee_token>&supplier_id=<id>
|
|
# (Employee logs in, acts on behalf of a specific Supplier)
|
|
#
|
|
identified_by :current_user, :current_entity_type, :current_supplier_id
|
|
|
|
def connect
|
|
token = request.params[:auth_token].presence
|
|
reject_unauthorized_connection unless token
|
|
|
|
if (employee = Employee.find_by_authentication_token(token))
|
|
self.current_user = employee
|
|
self.current_entity_type = :employee
|
|
# Employee acts on behalf of a supplier — passed as query param
|
|
self.current_supplier_id = request.params[:supplier_id]
|
|
elsif (user = User.find_by_authentication_token(token))
|
|
self.current_user = user
|
|
self.current_entity_type = :user
|
|
elsif (supplier = Supplier.find_by_authentication_token(token))
|
|
self.current_user = supplier
|
|
self.current_entity_type = :supplier
|
|
else
|
|
reject_unauthorized_connection
|
|
end
|
|
end
|
|
|
|
# Allow subscribing to the entity's own channel
|
|
def subscribe_to_self
|
|
case current_entity_type
|
|
when :user then "user_#{current_user.id}"
|
|
when :supplier then "supplier_#{current_user.id}"
|
|
when :employee then "employee_#{current_user.id}"
|
|
end
|
|
end
|
|
end
|
|
end
|