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

Ruby on Rails: redirect unauthenticated user to root instead of the sign in page

我正在使用 Rails 4 和 Devise 3。

我在路由文件中使用以下内容来防止未经身份验证的用户(未登录)访问页面:

authenticate :user do
   #page to protect 
end

这会将我重定向到 user/sign_in 页面,但我希望将用户重定向到根目录。所以,我也将以下内容添加到路线页面:

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('/').

以下可能与将用户重定向到 root 没有任何关系,但我想更多地解释一下为什么我要覆盖 sessions_controller 中的新方法。我将 sign_in 和 sign_up 视图移到了根页面(主页)。在这种情况下,我还需要破解错误消息,以便它们出现在主页中,而不是将用户重定向到 user/sign_in 来显示错误。为此我使用了 ajax。

更新

我要找的是这样的:

if user_authenticated? 
  #show the protected page
else  
  # redirect the user to the ROOT
end

您可以将 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 控制器和操作中处理适当的授权要求和身份验证要求。

很抱歉我没有理解你的问题,无论如何你可以这样做:

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 的 wiki 中截取的: https://github.com/plataformatec/devise/wiki/How-To%3a-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated