Ruby on rails actioncable在生产中不与Desive一起工作
我无法在我的ubuntu服务器上正常运行actioncable和docker 这似乎是一种身份验证错误,这是我的终端日志Ruby on rails actioncable在生产中不与Desive一起工作,ruby-on-rails,devise,actioncable,Ruby On Rails,Devise,Actioncable,我无法在我的ubuntu服务器上正常运行actioncable和docker 这似乎是一种身份验证错误,这是我的终端日志 There was an exception - NoMethodError(undefined method `user' for nil:NilClass) cable_1 | /var/www/acim/public/app/channels/application_cable/connection.rb:17:in `find_verifie
There was an exception - NoMethodError(undefined method `user' for nil:NilClass)
cable_1 | /var/www/acim/public/app/channels/application_cable/connection.rb:17:in `find_verified_user'
这是我的/app/chanels/application\u cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
private
def find_verified_user
if current_user = User.find_by(id: cookies.signed['user_token'])
current_user.id
else
reject_unauthorized_connection
end
end
end
end
# frozen_string_literal: true
# Set user_token cookie after sign in
Warden::Manager.after_set_user do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}_token"] = user.id
end
# Invalidate user.id cookie on sign out
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}_token"] = nil
end
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
# This is a websocket so we have no warden and no session here
# How to reuse the login made with devise?
# http://www.rubytutorial.io/actioncable-devise-authentication/
self.current_user = find_verified_user
logger.info("current_user: #{self.current_user.inspect}")
logger.add_tags "ActionCable", current_user.email
end
protected
def find_verified_user
verified_user = User.find_by(id: cookies.signed['user.id'])
if verified_user && cookies.signed['user.expires_at'] > Time.now
verified_user
else
reject_unauthorized_connection
end
end
end
end
# http://www.rubytutorial.io/actioncable-devise-authentication/
Warden::Manager.after_set_user do |user,auth,opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = user.id
auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now
end
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = nil
auth.cookies.signed["#{scope}.expires_at"] = nil
end
模块可应用
类连接
*这里是config/environments/production.rb*
Rails.application.configure do
#此处指定的设置将优先于config/application.rb中的设置。
#代码不会在请求之间重新加载。
config.cache_classes=true
#启动时立即加载代码。这将加载大部分Rails和
#您的应用程序在内存中,允许两个线程化web服务器
#而那些依靠写上拷贝来表现更好的人。
#Rake任务会自动忽略此选项以提高性能。
config.eager\u load=true
#完全错误报告被禁用,缓存被打开。
config.consive\u all\u requests\u local=true
config.action\u controller.perform\u caching=true
#确保主密钥已在任一环境中可用[“RAILS\u master\u key”]
#或者在config/master.key中。此密钥用于解密凭据(和其他加密文件)。
#config.require\u master\u key=true
#默认情况下,禁用从`/public`文件夹提供静态文件,因为
#Apache或NGINX已经处理了这个问题。
config.public\u file\u server.enabled=ENV['RAILS\u SERVE\u STATIC\u FILES']。是否存在?
#压缩Java脚本和CSS。
config.assets.js_compressor=:uglifier
#config.assets.css_compressor=:sass
#如果缺少预编译的资产,请不要回退到资产管道。
config.assets.compile=false
#`config.assets.precompile`和`config.assets.version`已移动到config/initializers/assets.rb
#支持从资产服务器提供图像、样式表和Java脚本。
#config.action\u controller.asset\u host=http://assets.example.com'
#指定服务器用于发送文件的标头。
#config.action_dispatch.x_sendfile_头='x-sendfile'#对于Apache
config.action_dispatch.x_sendfile_头='x-Accel-Redirect'#对于NGINX
#将上载的文件存储在本地文件系统上(有关选项,请参阅config/storage.yml)
config.active\u storage.service=:本地
#在主进程或域外安装操作电缆
#config.action\u cable.mount\u path=nil
config.action_cable.url='ws://192.168.99.100/cable'
config.action\u cable.allowed\u request\u origins=['http://192.168.99.100“,/http:\/\/192.168.99.100.*/,”http://localhost' ]
#config.action\u cable.url=[/ws:\/\/*/,/wss:\/\/*/]
#config.action\u cable.allowed\u request\u origins=[/http:\/\/*/,/https:\/\/*/]
#强制通过SSL访问应用程序,使用严格的传输安全,并使用安全cookie。
#config.force_ssl=true
#使用最低日志级别确保诊断信息的可用性
#当问题出现时。
config.log_level=:调试
#在所有日志行前添加以下标记。
config.log_标记=[:请求_id]
#在生产中使用不同的缓存存储。
#config.cache\u store=:mem\u cache\u store
#为活动作业使用真正的队列后端(以及每个环境的单独队列)
#config.active\u job.queue\u适配器=:resque
#config.active_job.queue_name_prefix=“ACIM_#{Rails.env}”
config.action\u mailer.perform\u caching=false
#忽略错误的电子邮件地址,不要引发电子邮件传递错误。
#将此设置为true,并将电子邮件服务器配置为立即传递以引发传递错误。
#config.action\u mailer.raise\u delivery\u errors=false
#为I18n启用区域设置回退(使任何区域设置的查找回退到
#无法找到翻译时的I18n.default_语言环境)。
config.i18n.fallbacks=true
#向已注册的侦听器发送弃用通知。
config.active\u support.deprecation=:notify
#使用默认的日志格式化程序,这样PID和时间戳就不会被抑制。
config.log_formatter=::Logger::formatter.new
#使用不同的记录器进行分布式设置。
#需要“syslog/logger”
#config.logger=ActiveSupport::TaggedLogging.new(Syslog::logger.new“app name”)
如果ENV[“RAILS\u LOG\u TO\u STDOUT”]存在?
logger=ActiveSupport::logger.new(标准输出)
logger.formatter=config.log\u格式化程序
config.logger=ActiveSupport::TaggedLogging.new(记录器)
结束
#迁移后不要转储架构。
config.active\u record.dump\u schema\u迁移后=false
#为公众服务的新公共管理局
# http://www.rubytutorial.io/actioncable-devise-authentication/
Warden::Manager.after_set_user do |user,auth,opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = user.id
auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now
end
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = nil
auth.cookies.signed["#{scope}.expires_at"] = nil
end
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = true
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
#config.action_cable.url = 'ws://192.168.99.100/cable'
#config.action_cable.allowed_request_origins = [ 'http://192.168.99.100', /http:\/\/192.168.99.100.*/, 'http://localhost' ]
config.action_cable.url = 'ws://192.168.99.100/cable'
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "ACIM_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# ne pas directement servir les fichiers public
# en utilisant ruby, mais passons par NGINX
config.public_file_server.enabled = false
config.assets.js_compressor = Uglifier.new(harmony: true)
end
Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb )
Sidekiq.configure_server do |config|
config.redis = { url: 'redis://192.168.99.100:6379' }
end
Sidekiq.configure_client do |config|
config.redis = { url: 'redis://192.168.99.100:6379' }
end
FROM ruby:2.5.1
# Install dependencies
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
ENV RAILS_ROOT /var/www/acim/public
RUN mkdir -p $RAILS_ROOT
RUN mkdir -p $RAILS_ROOT/log
RUN rm -rf /var/www/acim/public/tmp/pids/server.pid
# Set working directory, where the commands will be ran:
WORKDIR $RAILS_ROOT
# Setting env up
ENV RAILS_ENV='production'
ENV RACK_ENV='production'
# Adding gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install --jobs 20 --retry 5 --without development test
# Adding project files
COPY . .
RUN bundle exec rake assets:precompile
EXPOSE 3000
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]
version: '3'
services:
db:
image: postgres:9.6
environment:
- ACIM_DATABASE_PASSWORD=ACIM_2018
volumes:
- 'db:/var/lib/postgresql/data'
env_file:
- '.env'
expose:
- '5432'
ports:
- "7000:5432"
nginx:
image: nginx:latest
container_name: production_nginx
volumes:
- ./config/nginx/nginx.conf:/etc/nginx/nginx.conf
- public-content:/var/www/acim/public
ports:
- 80:80
- 443:443
links:
- web
# maildev:
# image: djfarrelly/maildev
# ports:
# - "2000:80"
redis:
image: redis
command: redis-server
volumes:
- 'redis:/data'
ports:
- "6379:6379"
sidekiq:
build: .
#command: sidekiq -C config/sidekiq.yml
command: bundle exec sidekiq
volumes:
- .:/ACIM
links:
- db
- redis
depends_on:
- db
- redis
env_file:
- '.env'
web:
build: .
volumes:
- bundle_cache:/bundle
- public-content:/var/www/acim/public
- .:/ACIM
ports:
- "5000:3000"
depends_on:
- db
- redis
env_file:
- '.env'
cable:
depends_on:
- 'redis'
- 'sidekiq'
build: .
command: puma -p 28080 cable/config.ru
ports:
- '28080:28080'
volumes:
- '.:/ACIM'
env_file:
- '.env'
volumes:
bundle_cache:
redis:
db:
public-content: