簡體   English   中英

Rails 4:登錄后設計重定向

[英]Rails 4: Devise redirect after sign in

我對控制器做了自己的身份驗證功能,它可以驗證的不僅僅是用戶是否已登錄(如果他們是管理員等)。 我發現的問題是,如果該人未登錄並嘗試訪問需要身份驗證的頁面,他們將成功重定向到登錄頁面,但是登錄后,他們不會被發送回原本的頁面。嘗試訪問。

我在ApplicationController添加了以下內容:

before_filter :store_location

def store_location
    p "storing location"
  # store last url - this is needed for post-login redirect to whatever the user last visited.
  return unless request.get? 
  if (request.path != "/users/sign_in" &&
      request.path != "/users/sign_up" &&
      request.path != "/users/password/new" &&
      request.path != "/users/password/edit" &&
      request.path != "/users/confirmation" &&
      request.path != "/users/sign_out" &&
      !request.xhr?) # don't store ajax calls
    session[:previous_url] = request.fullpath 
  end
end

def after_sign_in_path_for(resource)
  session["user_return_to"] || root_path
end

def new_authorize_employee
    if current_user.nil?
        redirect_to new_user_session_path, notice: "You must be signed in to access this page." 
    else
        unless current_user.is_employee?
            redirect_to root_path, notice: "You do not have permissions to access this page."
        end
    end
end

並在控制器中用戶正在嘗試訪問:

class EmployeesController < ApplicationController
    before_action :new_authorize_employee
    ...
end

但登錄后用戶仍被重定向到root_url如何更改身份驗證方法以允許重定向到用戶嘗試訪問的最后一頁?

Devise具有用於存儲位置的內置機制

class ApplicationController < ActionController::Base
  before_action :store_location!,
    unless: -> { devise_controller? || request.xhr? },
    if: -> { request.get? && is_navigational_format? }

  before_action :authenticate_user!, 
    unless: :devise_controller? # prevents a circular redirect


  private 

  def store_location!
    # from Devise::Controllers::StoreLocation
    # :user is the scope
    store_location_for(:user, request.fullpath)
  end
end

:store_location! 回調需要放在:authenticate_user!之前:authenticate_user! 作為:authenticate_user! 將停止過濾鏈並重定向,然后才能存儲位置。

if:unless:選項使您可以將條件應用於控制器回調。 請注意,這與ifunless ruby關鍵字不同。

devise_controller? is_navigational_format? 是設計助手。 devise_controller? 應該用於跳過任何與Devise相關的控制器中的回調,而不是將特定路徑列入黑名單。 默認的可導航格式為['*/*', :html]

不需要覆蓋after_sign_in_path_for因為它已經使用了存儲的位置:

def after_sign_in_path_for(resource_or_scope)
  stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope)
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM