Rails: Warden/Devise - How to capture the url before login/failed access

后端 未结 5 2394
天涯浪人
天涯浪人 2020-12-15 06:50

I am trying to figure out how to redirect a user to the page they logged in from (or failed to login) using Warden/Devise. I figure there is a session variable somewhere tha

5条回答
  •  有刺的猬
    2020-12-15 07:06

    here's the best I could come up with. Works perfectly also with facebook authentication. by adding more restrictions to the prepending of urls to the session variable you can remove more and more paths you don't want the user to return too (e.g. callbacks, splash pages, landing pages, etc)

    #ApplicationsController
    
    after_filter :store_location
    
    def store_location
      session[:previous_urls] ||= []
      # store unique urls only
      session[:previous_urls].prepend request.fullpath if session[:previous_urls].first != request.fullpath && request.fullpath != "/user" && request.fullpath != "/user/login" && request.fullpath != "/" && request.fullpath != "/user/logout" && request.fullpath != "/user/join" && request.fullpath != "/user/auth/facebook/callback"
      # For Rails < 3.2
      # session[:previous_urls].unshift request.fullpath if session[:previous_urls].first != request.fullpath 
      session[:previous_urls].pop if session[:previous_urls].count > 3
    end
    
    def after_sign_in_path_for(resource) 
      @url = session[:previous_urls].reverse.first
      if @url != nil
        "http://www.google.com" + @url
      else
        root_path
      end
    end
    

提交回复
热议问题