繁体   English   中英

设计-如何触发页面上的登录用户已经可以访问

[英]Devise - How to trigger a sign_in on page user already has access to

我正在使用Devise 3.5.2。 我有一个带有show动作的Item模型,任何人都可以访问( before_filter :authenticate_user!, except: :show )。 在显示页面上,我有一个按钮,该按钮使用jquery触发文件上传对话框。

我只希望此上载对话框对登录的用户有效。 如果用户已注销,然后单击“我希望它将该按钮带到我的登录页面”。 当他们登录时,我希望它带他们回到显示页面。

我如何才能做到这一点,所以单击此链接会将他们带到登录页面,然后在登录后将他们重定向到他们刚刚可以访问的页面?

<% unless current_user %>
  <%= link_to "Upload image", item_path @item, class: "btn btn-lg btn-success" %>
<% end %>

这将无法使用,因为他们已经可以访问此页面。

编辑:我尝试在此链接https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in,但似乎没有工作。

我的会话控制器看起来像这样。 也许我的create方法引起冲突?

class SessionsController < Devise::SessionsController

   def new
     self.resource = resource_class.new(sign_in_params)
     store_location_for(resource, params[:redirect_to])
     super
   end  


  def create
    self.resource = warden.authenticate!(auth_options)
    if resource.deactivated?
      set_flash_message(:notice, :reactivated) if is_flashing_format?
      resource.reactivate
    end
    sign_in(resource_name, resource)
    yield resource if block_given?
    respond_with resource, location: after_sign_in_path_for(resource)
  end  
end

听起来您需要一些控制器特定的代码。

当用户单击链接时,让相应的动作执行以下操作:

    def image_action # Whatever the action name is
      if current_user # current user is given to you by devise
        # Do stuff that a logged in user would do
      else
        # redirect to login page
      end
    end

想法是您将逻辑放在视图之外,而是让控制器为登录的用户提供适当的数据/页面,或者让未经身份验证的用户重定向到登录页面。

current_user是由devise提供给您的方法,该方法将评估当前发出请求的当前登录用户,如果该用户未登录,则为nil

如果发布您的控制器代码,我将淘汰更多示例代码,只是不想过于具体,以免造成混淆。

由于您已经在使用before_action :authenticate_user! 在您的控制器中以验证登录的用户..您只需要重写该方法即可重定向到您喜欢的任何页面,例如

在您的application_controller.rb

def authenticate_user!
  if user_signed_in?
    super
  else
    redirect_to whatever_path
  end
end

暂无
暂无

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

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