未捕获的投掷:装备的监护人

时间:2013-10-16 04:33:31

标签: ruby-on-rails devise

当我转到需要用户登录的路由时,我会在服务器日志中收到ArgumentError(uncaught throw:warden):

这是控制器代码:

class TracksController < ApplicationController
  include ActionController::Live
  before_filter :authenticate_user!, except: [:index, :show]
  before_filter :set_track, only: [:show, :edit, :update, :destroy, :queue]
  before_filter :ensure_current_user_is_owner, only: :queue

  def index
    if params[:tag]
      @tracks = Track.where(:is_private => false).order('created_at desc').tagged_with(params[:tag])

    else
      @tracks = Track.where(:is_private => false).order('created_at desc')
    end
  end

  # Public View
  def show
    @approved_stems = @track.stems.where(:approved => true).order('created_at desc')
    @comment = Comment.new
    @comments = @track.comments.order("created_at desc")
  end

  # Private queue
  def queue 
    @disapproved_stems = @track.stems.where(:approved => false).order('created_at desc')

  end

  def new
    @track = current_user.tracks.new
    @track.stems.build
  end

  def edit
    @track = current_user.tracks.find(params[:id])

  end

  def create
    @track = current_user.tracks.new(track_params)

    respond_to do |format|
      if @track.save
        format.html { redirect_to @track, notice: "Track created."}
      else
        format.html { render action: 'new'}
      end
    end
  end

  def update
    @track = current_user.tracks.find(params[:id])
    respond_to do |format|
      if @track.update(track_params)
        format.html { redirect_to @track, notice: 'Track was successfully updated.' }
      else
        format.html { render action: 'edit' }
      end
    end
  end

  def destroy
    @track = current_user.tracks.find(params[:id])
    @track.destroy
    respond_to do |format|
      format.html {redirect_to tracks_url}
    end
  end

  private

  def set_track
    @track = Track.find(params[:id])
  end

  def ensure_current_user_is_owner
    if current_user != @track.user
      redirect_to tracks_url, :alert => "You don't have permission!"
    end
  end

  def track_params
    # params[:track][:stems_attributes]['0'][:user_id] = current_user.id
    # params[:track][:stems_attributes]['0'][:approved] = true
    params.require(:track).permit(:tag_list, :cover_art, :title, :description, :bpm, :is_private, :stems_attributes => [:audio, :title, :user_id, :approved], :collabs_attributes =>[:email, :id, :_destroy])
  end
end

这是完整的服务器日志:

Completed 500 Internal Server Error in 2ms

NoMethodError (undefined method `call' for nil:NilClass):
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/live.rb:66:in `call_on_error'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/live.rb:136:in `rescue in block in process'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/live.rb:145:in `block in process'



ArgumentError (uncaught throw :warden):
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/warden-1.2.1/lib/warden/proxy.rb:128:in `throw'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/warden-1.2.1/lib/warden/proxy.rb:128:in `authenticate!'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/devise-3.0.0.rc/lib/devise/controllers/helpers.rb:48:in `authenticate_user!'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:427:in `_run__2832861654928389119__process_action__callbacks'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:80:in `run_callbacks'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/abstract_controller/callbacks.rb:17:in `process_action'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/rescue.rb:29:in `process_action'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activesupport-4.0.0/lib/active_support/notifications.rb:159:in `block in instrument'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activesupport-4.0.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activesupport-4.0.0/lib/active_support/notifications.rb:159:in `instrument'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/params_wrapper.rb:245:in `process_action'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-4.0.0/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/abstract_controller/base.rb:136:in `process'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/abstract_controller/rendering.rb:44:in `process'
  /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-4.0.0/lib/action_controller/metal/live.rb:132:in `block in process'

任何帮助都会受到赞赏,暂时停留在这个问题上。

编辑:

用户模型:

class User < ActiveRecord::Base
    attr_accessor :login
  mount_uploader :avatar, AvatarUploader
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :confirmable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]

  validate :sanitize_username, :on => :create
  validates :username, uniqueness: true
  validates :username, presence: true


  has_many :tracks, :dependent => :destroy


  def self.find_first_by_auth_conditions(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    else
      where(conditions).first
    end
  end



  private

  def sanitize_username
    self.username = username.downcase.gsub(" ", "")
  end

  def confirmation_required?
    true
  end

end

设计

# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
  # ==> Mailer Configuration
  # Configure the e-mail address which will be shown in Devise::Mailer,
  # note that it will be overwritten if you use your own mailer class with default "from" parameter.
  config.mailer_sender = "------------"

  # Configure the class responsible to send e-mails.
  # config.mailer = "Devise::Mailer"

  # ==> ORM configuration
  # Load and configure the ORM. Supports :active_record (default) and
  # :mongoid (bson_ext recommended) by default. Other ORMs may be
  # available as additional gems.
  require 'devise/orm/active_record'

  # ==> Configuration for any authentication mechanism
  # Configure which keys are used when authenticating a user. The default is
  # just :email. You can configure it to use [:username, :subdomain], so for
  # authenticating a user, both parameters are required. Remember that those
  # parameters are used only when authenticating and not when retrieving from
  # session. If you need permissions, you should implement that in a before filter.
  # You can also supply a hash where the value is a boolean determining whether
  # or not authentication should be aborted when the value is not present.
  # config.authentication_keys = [ :email ]

  # Configure parameters from the request object used for authentication. Each entry
  # given should be a request method and it will automatically be passed to the
  # find_for_authentication method and considered in your model lookup. For instance,
  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
  # The same considerations mentioned for authentication_keys also apply to request_keys.
  # config.request_keys = []

  # Configure which authentication keys should be case-insensitive.
  # These keys will be downcased upon creating or modifying a user and when used
  # to authenticate or find a user. Default is :email.
  config.case_insensitive_keys = [ :email ]

  # Configure which authentication keys should have whitespace stripped.
  # These keys will have whitespace before and after removed upon creating or
  # modifying a user and when used to authenticate or find a user. Default is :email.
  config.strip_whitespace_keys = [ :email, :username ]

  # Tell if authentication through request.params is enabled. True by default.
  # It can be set to an array that will enable params authentication only for the
  # given strategies, for example, `config.params_authenticatable = [:database]` will
  # enable it only for database (email + password) authentication.
  # config.params_authenticatable = true

  # Tell if authentication through HTTP Auth is enabled. False by default.
  # It can be set to an array that will enable http authentication only for the
  # given strategies, for example, `config.http_authenticatable = [:token]` will
  # enable it only for token authentication. The supported strategies are:
  # :database      = Support basic authentication with authentication key + password
  # :token         = Support basic authentication with token authentication key
  # :token_options = Support token authentication with options as defined in
  #                  http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
  # config.http_authenticatable = false

  # If http headers should be returned for AJAX requests. True by default.
  # config.http_authenticatable_on_xhr = true

  # The realm used in Http Basic Authentication. "Application" by default.
  # config.http_authentication_realm = "Application"

  # It will change confirmation, password recovery and other workflows
  # to behave the same regardless if the e-mail provided was right or wrong.
  # Does not affect registerable.
  # config.paranoid = true

  # By default Devise will store the user in session. You can skip storage for
  # :http_auth and :token_auth by adding those symbols to the array below.
  # Notice that if you are skipping storage for all authentication paths, you
  # may want to disable generating routes to Devise's sessions controller by
  # passing :skip => :sessions to `devise_for` in your config/routes.rb
  config.skip_session_storage = [:http_auth]

  # ==> Configuration for :database_authenticatable
  # For bcrypt, this is the cost for hashing the password and defaults to 10. If
  # using other encryptors, it sets how many times you want the password re-encrypted.
  #
  # Limiting the stretches to just one in testing will increase the performance of
  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
  # a value less than 10 in other environments.
  config.stretches = Rails.env.test? ? 1 : 10

  # Setup a pepper to generate the encrypted password.
  # config.pepper = "0db8498926b0e113b27106a661d47fcec43fcb3e9ed761e4b9fa8bd26fd5a97f5edd79362f2120364c4f0aa4dae321cc9ad1ab6219d3452c273dc3e35164362c"

  # ==> Configuration for :confirmable
  # A period that the user is allowed to access the website even without
  # confirming his account. For instance, if set to 2.days, the user will be
  # able to access the website for two days without confirming his account,
  # access will be blocked just in the third day. Default is 0.days, meaning
  # the user cannot access the website without confirming his account.
  config.allow_unconfirmed_access_for = 0.days

  # A period that the user is allowed to confirm their account before their
  # token becomes invalid. For example, if set to 3.days, the user can confirm
  # their account within 3 days after the mail was sent, but on the fourth day
  # their account can't be confirmed with the token any more.
  # Default is nil, meaning there is no restriction on how long a user can take
  # before confirming their account.
  # config.confirm_within = 3.days

  # If true, requires any email changes to be confirmed (exactly the same way as
  # initial account confirmation) to be applied. Requires additional unconfirmed_email
  # db field (see migrations). Until confirmed new email is stored in
  # unconfirmed email column, and copied to email column on successful confirmation.
  # config.reconfirmable = false

  # Defines which key will be used when confirming an account
  # config.confirmation_keys = [ :email ]

  # ==> Configuration for :rememberable
  # The time the user will be remembered without asking for credentials again.
  # config.remember_for = 2.weeks

  # If true, extends the user's remember period when remembered via cookie.
  # config.extend_remember_period = false

  # Options to be passed to the created cookie. For instance, you can set
  # :secure => true in order to force SSL only cookies.
  # config.rememberable_options = {}

  # ==> Configuration for :validatable
  # Range for password length. Default is 8..128.
  config.password_length = 8..128

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  # config.email_regexp = /\A[^@]+@[^@]+\z/

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  # config.timeout_in = 30.minutes

  # If true, expires auth token on session timeout.
  # config.expire_auth_token_on_timeout = false

  # ==> Configuration for :lockable
  # Defines which strategy will be used to lock an account.
  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  # config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  # config.unlock_keys = [ :email ]

  # Defines which strategy will be used to unlock an account.
  # :email = Sends an unlock link to the user email
  # :time  = Re-enables login after a certain amount of time (see :unlock_in below)
  # :both  = Enables both strategies
  # :none  = No unlock strategy. You should handle unlocking by yourself.
  # config.unlock_strategy = :both

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  # config.maximum_attempts = 20

  # Time interval to unlock the account if :time is enabled as unlock_strategy.
  # config.unlock_in = 1.hour

  # ==> Configuration for :recoverable
  #
  # Defines which key will be used when recovering the password for an account
  # config.reset_password_keys = [ :email ]

  # Time interval you can reset your password with a reset password key.
  # Don't put a too small interval or your users won't have the time to
  # change their passwords.
  config.reset_password_within = 6.hours

  # ==> Configuration for :encryptable
  # Allow you to use another encryption algorithm besides bcrypt (default). You can use
  # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
  # :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
  # and :restful_authentication_sha1 (then you should set stretches to 10, and copy
  # REST_AUTH_SITE_KEY to pepper).
  #
  # Require the `devise-encryptable` gem when using anything other than bcrypt
  # config.encryptor = :sha512

  # ==> Configuration for :token_authenticatable
  # Defines name of the authentication token params key
  # config.token_authentication_key = :auth_token

  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  # config.scoped_views = false

  # Configure the default scope given to Warden. By default it's the first
  # devise role declared in your routes (usually :user).
  # config.default_scope = :user

  # Set this configuration to false if you want /users/sign_out to sign out
  # only the current scope. By default, Devise signs out all scopes.
  # config.sign_out_all_scopes = true

  # ==> Navigation configuration
  # Lists the formats that should be treated as navigational. Formats like
  # :html, should redirect to the sign in page when the user does not have
  # access, but formats like :xml or :json, should return 401.
  #
  # If you have any extra navigational formats, like :iphone or :mobile, you
  # should add them to the navigational formats lists.
  #
  # The "*/*" below is required to match Internet Explorer requests.
  # config.navigational_formats = ["*/*", :html]

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :delete

  # ==> OmniAuth
  # Add a new OmniAuth provider. Check the wiki for more information on setting
  # up on your models and hooks.
  # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'

  # ==> Warden configuration
  # If you want to use other strategies, that are not supported by Devise, or
  # change the failure app, you can configure them inside the config.warden block.
  #
  # config.warden do |manager|
  #   manager.intercept_401 = false
  #   manager.default_strategies(:scope => :user).unshift :some_external_strategy
  # end

  # ==> Mountable engine configurations
  # When using Devise inside an engine, let's call it `MyEngine`, and this engine
  # is mountable, there are some extra configurations to be taken into account.
  # The following options are available, assuming the engine is mounted as:
  #
  #     mount MyEngine, at: "/my_engine"
  #
  # The router that invoked `devise_for`, in the example above, would be:
  # config.router_name = :my_engine
  #
  # When using omniauth, Devise cannot automatically set Omniauth path,
  # so you need to do it manually. For the users scope, it would be:
  # config.omniauth_path_prefix = "/my_engine/users/auth"
end

2 个答案:

答案 0 :(得分:1)

我处理它的方式:

1。经过身份验证的路由而不是控制器:

Liveexample::Application.routes.draw do
  devise_for :users 

  authenticate :user do
    resource :dashboard, controller: :dashboard, only: [:show] do
      get 'events', on: :member
    end
    root to: "dashboard#show", as: "root"
  end
end

authenticate指令将强制进行Devise身份验证。

另外,请注意as: "root"附录,这是Rails 4路由获取唯一名称所必需的

2。将JavaScripts更改为仅为其同名控制器加载:

<强>的application.js

//= require jquery
//= require jquery_ujs

注意缺少//= require tree .

<强> application.html.haml

= javascript_include_tag "application", controller_name unless controller_name == "sessions"

此处= javascript_include_tag "application"行已替换为= javascript_include_tag "application", controller_name。需要unless条件才能跳过对Devise会话控制器的不存在session.js文件的加载尝试。

3。更改了特定于环境的配置文件以启用服务静态资产,例如

<强> production.rb

config.serve_static_assets = true
config.assets.compile = true

希望它可能会有所帮助。

答案 1 :(得分:-1)

这是SO11152671的副本。我在那里贴了一个完整的答案。简而言之,您需要在实际的ControllerTest类中为Devise测试助手和Warden测试助手添加包含,而不是在test_helper.rb中。