[英]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.