[Rails] How to temporarily save the request URL of a user who is not logged in and return to that URL after logging in

The title is long. Here is a summary of friendly forwarding.

What is Friendly Forwarding?

It's a kind of process like "The page you requested, the page after login, but you haven't logged in yet. I'll guide you to the page you wanted to go to after logging in." Kind design that you often see. It's fine.

How do you make it?

The general flow is as follows.

  1. Temporarily save the requested URL
  2. Skip to the login screen and confirm your login
  3. Revert to the requested URL

Method definition

Prepare a method (1) for temporarily saving the request and a method (3) for returning to the temporarily saved URL. This time, in sessions_helper.rb, write as follows.

helpers/sessions_helper.rb



# 1.Temporarily save the requested URL
def store_location
  session[:forwarding_url] = request.original_url if request.get?
end

# 3.Revert to the requested URL
def redirect_back_or(default)
  redirect_to(session[:forwarding_url] || default)
  session.delete(:forwarding_url)
end

Save the requested URL (request.original_url) as session [: forwarding_url] in 1. ʻIf request.get?` limits the request type to GET actions only.

3 is the process to return to the temporarily saved URL or to return to the URL specified as the default. Even if the URL does not exist||After that, the URL set in default can be entered. Also, if you keep the session information, it will be read and strange at the next login, so the URL temporarily saved with session.delete (: forwarding_url) on the second line in the method Delete.

Temporarily save the requested URL + login confirmation

Call store_location to temporarily store the URL you are trying to access. Here, I will write it together with the description to check if the logged-in user is below private of ʻusers_controller.rb`.

users_controller.rb



class UsersController < ApplicationController
  before_action :user_login_required

・
・
・

private

def user_login_required
  unless logged_in? #When not logged in
    store_location #Temporarily save the URL here!
    flash[:danger] = "Please login" #Show flash message
    redirect_to login_url #Forced to send to login page
  end
end

Revert to the requested URL

Use redirect_back_or (default) to specify the transition destination after login. It is OK if you write the following in the place where the login process is performed.

controllers/sessions_controller.rb



def create
  user = User.find_by(email: params[:session][:email].downcase)
  if user && user.authenticate(params[:session][:password])
    log_in user
    params[:session][:remember_me] == '1' ? remember(user) : forget(user)
    flash[:success] = "You are now logged"
    #Specify the redirect destination below. default uses user here, but user_Can be written like url
    redirect_back_or user 
  else
    flash.now[:danger] = 'I failed to login'
    render 'new'
  end
end

This completes the implementation! If you dare to log in after deporting from an existing URL, you will be taken to that URL. Thank you for your support.

at the end

As mentioned above, I tried to reorganize each role in my own way so that it is easy to understand at a glance. I hope you find it helpful.

I referred to the following for implementation. Thank you very much.

-10.2.3 Friendly Forwarding (Rails Tutorial) -The most suitable technical blog in the world --Friendly forwarding

Recommended Posts

[Rails] How to temporarily save the request URL of a user who is not logged in and return to that URL after logging in
[rails devise] How to transition users who are not logged in to the login page
How to solve the problem when the value is not sent when the form is disabled in rails and sent
[Rails] How to get the URL of the transition source and redirect
How to solve the problem that the website image is not displayed after deploying to heroku on Rails 5
[Rails] How to get the user information currently logged in with devise
How to constrain the action of the transition destination when not logged in
[Rails] How to solve the time lag of created_at after save method
How to get the ID of a user authenticated with Firebase in Swift
How to make a unique combination of data in the rails intermediate table
[Forge] Addressing the problem that Render of self-made Entity is not displayed in 1.14.2 and 1.14.3
Method definition location Summary of how to check When defined in the project and Rails / Gem
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0
How to delete large amounts of data in Rails and concerns
[Rails] Read the RSS of the site and return the contents to the front
How to identify the path that is easy to make a mistake
How to solve the problem that it is not processed normally when nesting beans in Spring Batch
How to operate IGV using socket communication, and the story of making a Ruby Gem using that method
How to interact with a server that does not crash the app
How to test a private method in Java and partially mock that method
The story of forgetting to close a file in Java and failing
To you who lament that the conversion of JODConverter + LibreOffice is slow
Confirmation and refactoring of the flow from request to controller in [httpclient]
[Rails] About the error that the image is not displayed in the production environment
How to update user edits in Rails Devise without entering a password
How to change the maximum and maximum number of POST data in Spark
[Rails] Use devise to get information about the currently logged in user
How to change the value of a variable at a breakpoint in intelliJ
How to get the absolute path of a directory running in Java
[Rails] The cause of not being able to post was in form_with
Change the save destination of the image to S3 in the Rails app. Part 2
How to embed and display youtube videos in Rails (You can also get the URL you entered by editing)
How to resolve the error'ActionView :: Template :: Error (The asset "application.css" is not present in the asset pipeline.'" When precompiling Rails assets
What to do about "A server is already running ..." that happened without turning off the rails server in the terminal
How to insert a video in Rails
A solution to an error that makes you angry that you are not following the MySQL default setting ONLY_FULL_GROUP_BY in a production environment and it is not unique.
I tried to make a web application that searches tweets with vue-word cloud and examines the tendency of what is written in the associated profile
[rails devise] How to transition users who are not logged in to the login page
Prevent login users from transitioning to a specific page by entering a URL
How to constrain the action of the transition destination when not logged in
[Rails] How to temporarily save the request URL of a user who is not logged in and return to that URL after logging in
How to handle items in GSON that do not know whether they are single or array
How to prevent past dates from being entered in Rails forms
[jOOQ] How to CASE WHEN in the WHERE / AND / OR clause
[Rails] How to get the user information currently logged in with devise
How to get the setting value (property value) from the database in Spring Framework
How to get the date in java
graphql-ruby: How to get the name of query or mutation in controller Note
What to do if the changes are not reflected in the jar manifest file
How to set when "The constructor Empty () is not visible" occurs in junit
How to get the date from the JavaScript Date type that C # developers are addicted to
How to resolve errors that occur in the "Ruby on Rails" integration test
[Error] How to resolve the event that the screen does not transition after editing
How to set when "The constructor Empty () is not visible" occurs in junit
Is it mainstream not to write the closing tag of <P> tag in Javadoc?
Convert to a tag to URL string in Rails
[Rails] Button to return to the top of the page
How to implement a like feature in Rails
How to easily create a pull-down in Rails
How to use JQuery in js.erb of Rails6
After installing'devise''bootstrap' of gemfile with rails, what to do when url is an error
[Swift] How to simply describe dismiss that was not taught in the introductory book
[Rails] [Docker] Copy and paste is OK! How to build a Rails development environment with Docker
For those who want to use MySQL for the database in the environment construction of Rails6 ~.
[Rails] How to delete production environment MySQL data after putting it in the development environment
Processing when an ID that does not exist in the database is entered in the URL
How to save a file with the specified extension under the directory specified in Java to the list
Pass arguments to the method and receive the result of the operation as a return value
Library not loaded when trying to upgrade the version of ruby and rails s
[Rails] I want to display the link destination of link_to in a separate tab
How to deal with errors in Rails s could not find a JavaScript runtime.
How to implement a circular profile image in Rails using CarrierWave and R Magick
[Rails] How to display the weather forecast of the registered address in Japanese using OpenWeatherMap
A method that applies transforms in parallel to all elements and returns an array of return values that maintain their order