【问题标题】:Rails 4 devise - redirect user if not authenticatedRails 4 设计 - 如果未通过身份验证,则重定向用户
【发布时间】:2014-06-15 16:25:57
【问题描述】:

在 cmets_controller 中有 authenticate_user!

before_action :authenticate_user!

当用户点击创建评论时,他们现在被重定向到 users/sign_in 页面。

但是,我想将它们重定向到 root_url 并发出登录通知。主页上有登录按钮(FB 和 G+)。

我查看了this,但是当我实现它时,我只是得到一个具有相同 URL 和 Completed 401 Unauthorized 的黑页。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 devise


    【解决方案1】:

    您可以将authenticate_user! 方法添加到application_controller.rb

    class ApplicationController < ActionController::Base
    
      protected
      def authenticate_user!
        redirect_to root_path, notice: "You must login" unless user_signed_in?
      end
    end
    

    【讨论】:

    • 我认为这不是authenticate_user的正确定义!你需要传递一个参数
    【解决方案2】:

    我向 Devise wiki 添加了一个页面,显示了使用失败应用程序执行此操作的正确方法:Redirect to new registration (sign up) path if unauthenticated

    关键是重写route方法,像这样:

    # app/lib/my_failure_app.rb
    class MyFailureApp < Devise::FailureApp
      def route(scope)
        :new_user_registration_url
      end
    end
    

    然后让 Devise 使用你的失败应用:

    # config/initializers/devise.rb
    config.warden do |manager|
      manager.failure_app = MyFailureApp
    end
    

    这种方法比在控制器中覆盖 authenticate_user! 更可取,因为它不会破坏 Devise 所做的很多“幕后”工作,例如存储尝试的 URL,以便在成功登录后重定向用户。

    具有多种用户类型

    如果您有 AdminUser 设计资源,您可能希望为管理员保留默认的“新会话”功能。通过检查正在处理的范围类型,您可以很容易地做到这一点:

    # app/lib/my_failure_app.rb
    class MyFailureApp < Devise::FailureApp
      def route(scope)
        scope.to_sym == :user ? :new_user_registration_url : super
      end
    end
    

    【讨论】:

      【解决方案3】:

      cmets_controller.rb

          before_filter :loged_in?, :only => [:create, :edit, :destroy] #customize to fit your needs
      
          private
      
          def loged_in?
            redirect_to root_path, notice: 'Your have to log in' unless current_user
          end
      

      它将检查 current_user 是否存在,如果用户已登录,它将检查,否则重定向到根路径并给出通知。

      【讨论】:

        猜你喜欢
        • 2021-06-19
        • 2021-10-11
        • 1970-01-01
        • 2020-07-05
        • 1970-01-01
        • 2023-01-20
        • 2012-11-12
        • 2016-12-30
        • 1970-01-01
        相关资源
        最近更新 更多