before_filter require_login创建一个无限循环

时间:2013-09-30 15:00:51

标签: ruby-on-rails ruby devise cancan rails-admin

我是ruby和Rails的新手。我在我的应用程序中使用Devise和CanCan以及Rails_Admin。 我正在尝试做 - >如果用户已经登录,并且它是管理员,则重定向到rails_admin_path,如果它不是管理员但只是用户然后重定向到'upload_path',如果它没有登录然后重定向到sign_in路径,但可能是由于我缺乏knoledge,我正在创建一个无限重定向循环。即使我尝试在没有“require_login”过滤器的情况下访问sign_in。

这是我到目前为止所做的事情: application_controller.rb

class ApplicationController < ActionController::Base
  before_filter :require_login
  protect_from_forgery

 #IDEA 1
 #def require_login
 #   if current_user.role? == 'Administrator'
 #      redirect_to rails_admin_path
 #   elsif current_user.role? == (('C1' or 'D1') or ('M1' or 'M2'))
 #      redirect_to upload_path
 #   end
 # end  

#I saw this somewhere and It doesn't work either
 def require_login
   redirect_to new_user_session_path, alert: "You must be logged in to perform this action" if current_user.nil?
 end
    rescue_from CanCan::AccessDenied do |e|
   redirect_to new_user_session_path, alert: e.message
   end

end

的routes.rb

Siteconfigurationlistgenerator::Application.routes.draw do

  mount RailsAdmin::Engine => '/admin', :as => 'rails_admin'

 devise_for :users
  # The priority is based upon order of creation:
  # first created -> highest priority.

  match 'upload' => 'upload_file#new'
.
.
.

ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
   #Define abilities for the passed in user here.
   user ||= User.new #guest user (not logged in)
   #a signed-in user can do everything
    if user.role == 'Administrator'
       #an admin can do everything
         can :manage, :all
         can :access, :rails_admin   # grant access to rails_admin
         can :dashboard              # grant access to the dashboard
    elsif user.role == (('C1' or 'M1') or ('D1' or 'M1'))
       # can :manage, [ProductList, Inventory]
       # can :read, SiteConfigurationList
   #  end
   end

  end

当我运行rake路由时,我得到了Devise和Rails_admin路由的路由,以及“上传”路由。 我真的试图解决这个愚蠢的错误但老实说我用完了想法。我很感激您能提供给我的任何帮助。先感谢您。

1 个答案:

答案 0 :(得分:3)

问题是您的ApplicationController中有一个before_filter需要用户登录。基本上,您要求用户在访问登录页面之前登录。

您可以使用devise的内置方法:authenticate_user来解决此问题:

before_filter :authenticate_user!

或者你可以指定你的before_filter没有在DeviseController的动作上运行。

before_filter :require_login, :unless => :devise_controller?