[英]Rails 4 devise - redirect user if not authenticated
There is authenticate_user! 有authenticate_user! in a comments_controller.
在comment_controller中。
before_action :authenticate_user!
When a user clicks to create a comment, they are now redirected to users/sign_in page. 现在,当用户单击以创建评论时,他们将被重定向到用户/登录页面。
But, I want to redirect them to root_url and put a notice to log in. There are login buttons(FB and G+) on home page. 但是,我想将它们重定向到root_url并发出登录通知。主页上有登录按钮(FB和G +)。
I've looked at this , but when I implement it, I just get a black page with the same URL and Completed 401 Unauthorized . 我看这个 ,但是当我实现它,我只是得到一个黑色的页面相同的URL,并完成401未授权 。
You can add authenticate_user!
您可以添加
authenticate_user!
method to the application_controller.rb
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
I added a page to the Devise wiki showing the correct way to do this with a failure app: Redirect to new registration (sign up) path if unauthenticated 我在Devise Wiki中添加了一个页面,该页面显示了使用失败的应用程序执行此操作的正确方法: 如果未经身份验证,则重定向到新的注册(注册)路径
The key is to override the route
method, like so: 关键是要覆盖
route
方法,如下所示:
# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
def route(scope)
:new_user_registration_url
end
end
and then have Devise use your failure app: 然后让Devise使用您的失败应用程序:
# config/initializers/devise.rb
config.warden do |manager|
manager.failure_app = MyFailureApp
end
This approach is preferable to overriding authenticate_user!
此方法优于覆盖
authenticate_user!
in your controller because it won't clobber a lot of "behind the scenes" stuff Devise does, such as storing the attempted URL so the user can be redirected after successful sign in. 在控制器中,因为它不会破坏Devise所做的许多“幕后”工作,例如存储尝试的URL,以便在成功登录后可以重定向用户。
If you have Admin
and User
Devise resources, you'll probably want to keep the default "new session" functionality for admins. 如果您拥有
Admin
和User
Devise资源,则可能需要为管理员保留默认的“新会话”功能。 You can do so quite easily by checking what type of scope is being processed: 您可以通过检查正在处理的范围类型来轻松完成此操作:
# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
def route(scope)
scope.to_sym == :user ? :new_user_registration_url : super
end
end
comments_controller.rb comments_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
it will check if current_user exists, which it will if a user is signed in, otherwise redirects to root path with given notice. 它将检查current_user是否存在,如果用户已登录,它将进行检查,否则将在给定通知的情况下重定向到根路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.