如果用户未通过 Devise 进行身份验证,则重定向到登录页面 [英] Redirect to log in page if user is not authenticated with Devise
问题描述
我正在使用 Devise 和 Ruby on Rails.
I'm using Devise with Ruby on Rails.
如果未经身份验证的用户尝试访问需要身份验证的页面,推荐将其重定向到 session#new 页面的方法是什么?
What is the recommended way to redirect unauthenticated users to the sessions#new page if they attempt to access a page that requires authentication?
现在我收到一条错误消息,指出没有路由与他们尝试访问的路由匹配(导致生产中出现 404 错误).
Right now I get an error that says no route matches the one they attempt to access (leading to a 404 error in production).
推荐答案
只需将此方法添加到 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
另一个你想要的控制器上调用这个方法.
And you can call this method on before_filter
another controllers you want.
例如:
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
Don't forget add login_path
into routes.rb
devise_scope :user do
match '/sign-in' => "devise/sessions#new", :as => :login
end
注意:我在玩设计时总是使用这种方式来验证我的应用程序..(rails 3.2 和 rails 4.0.1)
note : I always use this way when play with devise for my apps authentication.. (rails 3.2 and rails 4.0.1)
这篇关于如果用户未通过 Devise 进行身份验证,则重定向到登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!