如果用户没有使用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.
如果尝试访问页面,将未经身份验证的用户重定向会话#新页面的推荐方法是什么这需要认证?
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
Just simple add this method to 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
into 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屋!