![](/img/trans.png)
[英]Devise: Redirect authenticated users to a single subdomain in Rails 5
[英]Rails 4 devise - redirect user if not authenticated
有authenticate_user! 在comment_controller中。
before_action :authenticate_user!
现在,当用户单击以创建评论时,他们将被重定向到用户/登录页面。
但是,我想将它们重定向到root_url并发出登录通知。主页上有登录按钮(FB和G +)。
我看这个 ,但是当我实现它,我只是得到一个黑色的页面相同的URL,并完成401未授权 。
您可以添加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
我在Devise Wiki中添加了一个页面,该页面显示了使用失败的应用程序执行此操作的正确方法: 如果未经身份验证,则重定向到新的注册(注册)路径
关键是要覆盖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,以便在成功登录后可以重定向用户。
如果您拥有Admin
和User
Devise资源,则可能需要为管理员保留默认的“新会话”功能。 您可以通过检查正在处理的范围类型来轻松完成此操作:
# 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
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是否存在,如果用户已登录,它将进行检查,否则将在给定通知的情况下重定向到根路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.