Ruby on Rails:将未经身份验证的用户重定向到主页而不是登录页面

3
我是Rails 4和Devise 3的用户。
在路由文件中,我使用如下代码来防止未经认证(未登录)的用户访问某个页面:
authenticate :user do
   #page to protect 
end

这会将我重定向到用户/登录页面,但我希望用户被重定向到根目录。因此,我还在路由页面上添加了以下内容:
get 'user/sign_in' => redirect('/')

但这将会破坏我在sessions_controllers中所做的工作:
def new
    return render :json => {:success => false, :type => "signinn", :errors => ["You have to confirm your email address before continuing."]}
end

这将不再显示。因此,我希望有另一种解决方案,可以直接将用户重定向到根目录,而无需使用authenticate:user,然后get'user/sign_in' => redirect('/')
以下内容可能与将用户重定向到根目录无关,但我想更多地解释为什么要在sessions_controller中覆盖new方法。我将登录和注册视图移动到了主页。在这种情况下,我还需要修改错误消息,使它们出现在主页上,而不是重定向用户到user/sign_in以显示错误。我使用ajax实现了这一点。
更新
我正在寻找的是像这样的东西:
if user_authenticated? 
  #show the protected page
else  
  # redirect the user to the ROOT
end
2个回答

3
您可以将您的devise范围设置成类似于以下内容。
  devise_scope :user do
    authenticated :user do
      root :to => 'pages#dashboard', as: :authenticated_root
    end
    unauthenticated :user do
      root :to => 'session#new', as: :unauthenticated_root
    end
  end

编辑(根据新信息):

如果您在routes.rb中有类似以下内容:

root to: 'visitors#index`

那么你可以在你的visitors_controller.rb中添加类似这样的内容。
class VisitorsController < ApplicationController
  def index
    if current_user
      redirect_to some_authenticated_path
    else
      # business logic here
    end
  end
end

some_authenticated_path控制器和动作中,您仍然需要处理适当的授权要求和身份验证要求。


不太符合我的需求。这将使用session#new,我更喜欢避免使用它。您能否请检查我在问题中添加的更新?希望那能更好地解释我的需求。谢谢。 - hello_its_me
在你的根操作中,你可以加入一个if current_user的重定向语句,否则执行普通的操作。 - kobaltz

2
抱歉,我没有理解你的问题,不过你可以像这样做:

很抱歉,我没有理解您的问题。无论如何,您可以尝试以下方法:

class CustomFailure < Devise::FailureApp
    def route(scope)
      #return super unless [:worker, :employer, :user].include?(scope) #make it specific to a scope
       new_user_session_url(:subdomain => 'secure')
    end

    # You need to override respond to eliminate recall
    def respond
      if http_auth?
        http_auth
      else
        redirect
      end
    end
  end

在config/initializers/devise.rb文件中:

  config.warden do |manager|
    manager.failure_app = CustomFailure
  end

这是从devise的维基页面中摘录的内容: https://github.com/plataformatec/devise/wiki/How-To%3a-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated 本页介绍了如何在用户未被验证时重定向到特定页面的方法。

这仍然会将用户重定向到 user/sign_in 页面,对吗? - hello_its_me

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接