Giter VIP home page Giter VIP logo

Comments (9)

Lianowar avatar Lianowar commented on June 15, 2024

Also, i found that i can't correctly initialize session and retrieve user (devise/warden). cookies.encrypted[app_cookies_key] is empty.
I think this because i use redis sessions store, and i need generate key and get value from redis in explicit way.
Do you found some similar problems?

from anycable-rails.

Lianowar avatar Lianowar commented on June 15, 2024

For redis stored session need use Marshal

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

    def connect
      self.current_user = find_verified_user || reject_unauthorized_connection
    end

    protected
    def find_verified_user
      app_cookies_key = Rails.application.config.session_options[:key] ||
        raise("No session cookies key in config")

      env['rack.session'] = Marshal.load(Redis.current.get(cookies[app_cookies_key]))
      Warden::SessionSerializer.new(env).fetch(:user)
    end
  end
end

I think there is no security issues during the value of session is store in Redis

from anycable-rails.

palkan avatar palkan commented on June 15, 2024

i found that i can't correctly initialize session and retrieve user (devise/warden). cookies.encrypted[app_cookies_key] is empty.

Do you run AnyCable and Rails servers using different domains/subdomain? Have you configured your cookies to support multiple domains? Check this doc: https://docs.anycable.io/#/troubleshooting?id=my-websocket-connection-fails-with-quotauth-failedquot-error

may be needed to add handle_subscribe method mention on documentation?

Nope. It should be added by anycable-rails:

alias handle_subscribe subscribe_to_channel

Looks like the extension hasn't been loaded for some reason. Could you please share the contents of your Gemfile and config/application.rb and config/environments/<environment>.rb file?

after i added this method

Could you provide an code example of how and where did you add this method?

from anycable-rails.

Lianowar avatar Lianowar commented on June 15, 2024

Do you run AnyCable and Rails servers using different domains/subdomain? Have you configured your cookies to support multiple domains? Check this doc: https://docs.anycable.io/#/troubleshooting?id=my-websocket-connection-fails-with-quotauth-failedquot-error

Hi! No, at first i trying to authorize user on localhost and i can take not encrypted cookies, it was provided in request variable, but encrypted cookies doesn't contain session key. I was fix it by getting key from regular cookies, take content by this key from redis and parse it by Marshal.

Nope. It should be added by anycable-rails:

But what method must be defined in my channel? I was tried to define subscribed and follow methods as mentioned at documentation, but not any of this methods was fired, but just after i added handle_subscribe it start worked as expected.

module Content
  class AlertsChannel < ApplicationCable::Channel
    def handle_subscribe
      stream_from Channels.alerts
    end
  end
end

this is worked, because i override handle_subscribe method

Could you provide an code example of how and where did you add this method?

Gemfile

source 'https://rubygems.org'
ruby '2.6.2'

gem 'dotenv-rails', groups: %i[development test]

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?('/')
  "https://github.com/#{repo_name}.git"
end
## RAILS
gem 'puma', '~> 3.7'
gem 'rails', '5.2.3'
gem 'rake', '12.3.2'

## Views
gem 'slim-rails', '3.1.1'

## SERIALIZATION
gem 'jb', '0.7.0'
gem 'jbuilder', '~> 2.5'

##  AUTH
gem 'cancancan', '2.2.0'
gem 'devise', '4.5.0'

## DB
gem 'pg', '~> 0.18'

## Pretty Urls
gem 'friendly_id', '~> 5.2.0'

## UTILITY
gem 'config', '1.4.0'
gem 'nokogiri', '1.10.0'
gem 'rest-client', '2.0.2'
gem 'discard', '~> 1.0'

## INTEGRATION
gem 'aws-sdk-rails', '2.0.1'
gem 'aws-sdk-s3', '1.16.1'
gem 'stripe', '3.21.0'
gem 'taxamo-ns', '2.3.6'
gem 'telestream_cloud', '2.0.0.1'
gem 'zencoder', '~> 2.0'

# TODO: check gem updates. Its still tech-preview gem
gem 'wsc_sdk', '1.3.1'

## CACHE
gem 'redis', '>= 4.0'
gem 'redis-rails', '5.0.2'

## SEARCH
gem 'hairtrigger'
gem 'pg_search', '2.1.2'
gem 'ransack', github: 'activerecord-hackery/ransack'
gem 'searchlight', '4.1.0'

## WORKERS
gem 'sidekiq', '5.2.2'
gem 'sidekiq-cron', '1.0.4'
gem 'sidekiq-unique-jobs', '~> 6.0.0.rc6'

gem 'rack-cors', require: 'rack/cors'
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby]

## Logging
gem 'awesome_print', '1.8.0'
# gem 'rails_semantic_logger', '4.3.3'

## Ordering
gem 'acts_as_list', '0.9.17'

# Thumbnails
gem 'carrierwave', '~> 1.0'
gem 'fog-aws', '3.3.0'
gem 'mini_magick', '4.7.2'

## Translations
gem 'globalize', git: 'https://github.com/IlyasValiullov/globalize.git', branch: 'feature/create-source-columns' #'5.2.0'
gem 'globalize-accessors', '0.2.1'

## Pagination
gem 'kaminari', '1.0.1'

## Versioning
gem 'globalize-versioning', '0.3.0'
gem 'paper_trail', '10.1'

## Exceptions
gem 'exception_notification'

## State machine
gem 'aasm', '5.0.2'

## Firebase cloud messaging
gem 'fcm', '0.0.6'

## Websockets
gem 'anycable-rails'

gem 'paranoia', '2.4.1'
gem 'sidekiq-status', '1.1.1'

# Groups

group :production do
  gem 'couchbase', '1.3.15'
  gem 'rack-timeout', '0.5.1'
  gem 'slack-notifier'
  gem 'newrelic_rpm'
end

group :development, :test do
  gem 'better_errors'
  gem 'binding_of_caller'
  gem 'byebug', platforms: %i[mri mingw x64_mingw]
  gem 'selenium-webdriver'

  ## TEST
  gem 'cucumber-rails', require: false
  gem 'database_cleaner'
  gem 'factory_bot_rails', '~> 4.0'
  gem 'faker', git: 'https://github.com/stympy/faker.git', branch: 'master'
  gem 'guard-rspec', require: false
  gem 'rspec-rails', '~> 3.7'
  gem 'simplecov', require: false, group: :test
  gem 'timecop'
  gem 'stripe-ruby-mock', '~> 2.5.6', require: 'stripe_mock'

  # rails swagger api gem
  gem 'rswag-specs'

  gem 'test-prof'
  gem 'stackprof', '>= 0.2.9', require: false
end

gem 'rswag-api'
gem 'rswag-ui'

group :development do
  gem 'brakeman'
  gem 'html2slim'
  gem 'letter_opener'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'rubocop', '0.62.0'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'traceroute'
  gem 'web-console', '>= 3.3.0'

  gem 'bullet'
  gem 'hirb'
  gem 'lol_dba'
end

application.rb

require_relative 'boot'

require 'rails'
# Pick the frameworks you want:
require 'active_model/railtie'
require 'active_record/railtie'
require 'action_mailer/railtie'
require 'action_cable/engine'
require 'anycable/rails/compatibility'

Bundler.require(*Rails.groups)

module ****
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    config.api_only = true
    config.middleware.insert_after Rack::Runtime, Rack::MethodOverride
    config.middleware.insert_before Rack::Head, ActionDispatch::Cookies
    config.middleware.insert_before Rack::Head, ActionDispatch::Session::RedisStore,
                                    key: '***',
                                    servers: [{ host: ENV['RAILS_REDIS_HOST'] || '127.0.0.1',
                                                port: ENV['RAILS_REDIS_PORT'] || '6379' }]

    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

    config.i18n.available_locales = %i[en ru es ar]
    config.i18n.fallbacks = [:en]
    config.i18n.default_locale = :en

    # Add config/routes directory
    config.autoload_paths << Rails.root.join('config/routes')
    config.eager_load_paths << Rails.root.join('config/routes')

    config.generators do |g|
      g.test_framework :rspec
    end
  end
end

environment/development.rb

Rails.application.configure do
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  if Rails.root.join('tmp/caching-dev.txt').exist?
    config.action_controller.perform_caching = true
    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
    }
  else
    config.action_controller.perform_caching = false
    config.cache_store = :null_store
  end

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false
  config.action_mailer.perform_caching = false

  # Using AWS Simple Email Service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.default_url_options = { host: 'localhost:3000' }

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Raises error for missing translations
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  config.file_watcher = ActiveSupport::EventedFileUpdateChecker

  config.action_cable.url = ENV.fetch('WEBSOCKET_URL', 'ws://localhost:3334/cable')
  config.action_cable.allowed_request_origins = ENV.fetch('WEBSOCKET_ORIGINS', 'http://localhost:3004,http://localhost:3000').split(',')

  config.after_initialize do
    Bullet.enable = true
    Bullet.bullet_logger = true
    Bullet.console = true
    Bullet.rails_logger = true
  end

  # STDOUT.sync = true
  # config.rails_semantic_logger.add_file_appender = false
  # config.semantic_logger.add_appender(io: STDOUT, level: config.log_level, formatter: config.rails_semantic_logger.format)
  # config.rails_semantic_logger.semantic   = false
end

from anycable-rails.

palkan avatar palkan commented on June 15, 2024

Thanks for sharing!
I will try to reproduce the bug locally, and, hopefully, will come back with the solution.

from anycable-rails.

Lianowar avatar Lianowar commented on June 15, 2024

Thank you! Currently i make it worked as i wanted, but im not sure about security issues or bugs.

from anycable-rails.

palkan avatar palkan commented on June 15, 2024

I found the cause of the problem.

This line in your in application.rb:

require 'anycable/rails/compatibility'

It turned out, that runtime compatibility checks break the AnyCable subscription behaviour. Compatibility checks are meant for using with Action Cable, first of all. That's why we didn't catch the problem earlier.

So, quick fix is to remove the compatibility checks for now.

The proper fix will be included in the next release (see the attached PR #97).

from anycable-rails.

Lianowar avatar Lianowar commented on June 15, 2024

Wow, thank you! May be i need add redis sessions example in documentation?

from anycable-rails.

palkan avatar palkan commented on June 15, 2024

May be i need add redis sessions example in documentation?

Let’s add a link to this issue/comment under the example here: https://github.com/anycable/docs.anycable.io/blob/master/docs/using_with_rails.md#devise-authentication

Smth, like:

If you’re using Redis session store, check out the example from this comment.

from anycable-rails.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.