繁体   English   中英

如果用户未使用Devise进行身份验证,则重定向到登录页面

[英]Redirect to log in page if user is not authenticated with Devise

我正在使用Devise和Ruby on Rails。

如果未经身份验证的用户尝试访问需要身份验证的页面,建议将其重定向到会话#new页面?

现在我收到一条错误,指出没有路由匹配他们尝试访问的路由(导致生产中出现404错误)。

只需将此方法添加到application_controller.rb

  protected
  def authenticate_user!
    if user_signed_in?
      super
    else
      redirect_to login_path, :notice => 'if you want to add a notice'
      ## if you want render 404 page
      ## render :file => File.join(Rails.root, 'public/404'), :formats => [:html], :status => 404, :layout => false
    end
  end

你可以在before_filter上调用你想要的另一个控制器。

例如:

class HomesController < ApplicationController
  before_filter :authenticate_user!
  ## if you want spesific action for require authentication
  ## before_filter :authenticate_user!, :only => [:action1, :action2]
end

不要忘记将login_path添加到routes.rb

devise_scope :user do
  match '/sign-in' => "devise/sessions#new", :as => :login
end

注意:我总是使用这种方式玩我的应用程序认证设计..(rails 3.2和rails 4.0.1)

你可以像GeekTol那样写,或者只是放

before_action :authenticate_user!

在你的控制器中。

在这种情况下,devise使用默认的authenticate_user! 方法,将重定向到“user_session_path”并使用默认的Flash消息。

没有必要重写authenticate_user! 方法,除非你想自定义它。

我以为你可以添加:before_action:authenticate_user! 到需要用户登录的每个控制器。

我是Rails初学者,但我在自己的搜索中找到了这个,并且它在我的应用程序中运行良好。

您应该参考Devise自己的如何: 如何:当用户无法进行身份验证时,重定向到特定页面

我能想到的另一个选择是创建一个包装受保护路由的路由约束。 你最好坚持Devise的方式,但这是一个例子:

#On your routes.rb
constraints(Constraints::LoginRequired) do
  get '/example' 
end

#Somewhere like lib/constraints/login_required.rb
module Constraints
  class LoginRequired
    def self.matches?(request)
      #some devise code that checks if the user is logged in
    end 
  end
end

在config / routes.rb中添加此代码devise_for :usersresources :users ,您可以在视图中生成设计。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM