module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user, :regia_session

    def connect
      if (regia_token = request.params[:regia_token].presence)
        self.regia_session = Sessions::RegiaAccess.find_session_by_token(regia_token)
        reject_unauthorized_connection unless regia_session
        return
      end

      payload = JsonWebToken.decode(token_from_header)
      self.current_user = User.find_by(id: payload[:user_id]) if payload
      reject_unauthorized_connection unless current_user
    end

    private

    def token_from_header
      request.headers["Authorization"].to_s.delete_prefix("Bearer ").presence
    end
  end
end
