如何:当用户无法进行身份验证时重定向到特定页面(设计rails gem)

时间:2016-05-26 01:37:09

标签: ruby-on-rails redirect login devise

我只想到了这一点,设计的指示并不是最好的。我在下面回答了我自己的问题

进入lib

  class CustomFailure < Devise::FailureApp
    def redirect_url
       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.warden do |manager|
    manager.failure_app = CustomFailure
  end

进入application.rb

config.autoload_paths << Rails.root.join('lib')

2 个答案:

答案 0 :(得分:1)

如果用户未登录,代码中的第一个将不会重定向您的路由。这是一个单独的问题,可以在继承到registrations_controller的自定义控制器内修复。当用户登录失败时,这将做的是重定向。 IE输入错误的密码&gt;重定向到新页面。

对于第一个代码分支,在lib文件夹(顶级)中创建一个名为custom_failure.rb的应用程序并将该代码粘贴到其中。

代码的第二个分支进入

  

/Users/admin/acltc_projects/roomkick/config/initializers/devise.rb   搜索

使用cmd f或ctrl f

warden do并删除warden do上的#和&#34; end&#34;线。 将manager.failure_app = CustomFailure粘贴在监狱长下面。在application.rb中的config / locals下,在模块中添加config.autoload_paths << Rails.root.join('lib')。 最后回到lib里面的app并修改session_url的行new_user_session_url(:subdomain => 'secure'),你可以直接将它修改为你想要的路径。 重新启动服务器并测试应用程序。 如果这有帮助就Upvote!

答案 1 :(得分:0)

检查设计文档https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated

  

如果用户不可验证,您可以重定向到特定页面。

     

对于此示例,我们希望将整个URL与特定URL一起使用   子域。默认情况下,Devise使用路径而不是整个URL。该   解决方法是使用从Devise继承的自定义失败应用程序   失败的应用程序。

class CustomFailure < Devise::FailureApp
    def redirect_url
       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

希望它会有所帮助。