[RUBY] Rails tutorial (6th edition) Background operation of login function
table of contents
- Create new account
- ** Login (including Friendly Forwarding and permanent login) **
- Edit Profile
- Reset Password (https://qiita.com/akarin0519/items/ea873bb165ed4099a40e)
- Posting a micro post
- Follow and unfollow
2. Login
Operation screen
The operation of the login function with Friendly Forwarding and persistent login proceeds in the following two steps.
- Click a link that requires login (for example, edit profile) to display the login screen.
- Enter the required information on the login screen and press the send button to complete the login and display the link destination screen that you originally tried to access.
Background operation
The operation executed in each of the above steps is as follows.
- Send a GET request to a URL associated with an action that requires a login, such as the edit action in the Users controller, to see if the user is logged in, that is, if there is a session (session [: user_id]). If there is no session, store the url of the destination that tried to access in session [: forwarding_url]. Then, the redirect is made to login_url (GET request to/login path), the new action in SessionsController is executed, and the view (/sessions_controller/new.html.erb) corresponding to the new action, that is, the login screen is displayed. To log in.
- When the user fills in the required information in the login form and clicks the submit button, a POST request to the/login path is sent and the create action in the Sessions Controller is executed. In this create action, first, the corresponding user is searched from the DB using the email address (params [: session] [: email]) entered in the form as a clue. If the corresponding user exists, and the digest value of the password (params [: session] [: password]) received from the input form matches the password_digest registered in the DB (= authentication success), In addition, if the account is already activated, log in, that is, set up a session (session [: user_id] = user.id) and check the persistent login checkbox (logical value of remember_me key). Then, if the remember_me key is true, generate remember_token, save the digested value (remember_digest) in DB, and store the user ID and remember_token in cookies. On the other hand, if the remember_me key is false, set remember_digest to nil and delete the user ID and remember_token stored in cookies. Finally, if there is a URL that you tried to access before the login screen is displayed (session [: forwarding_url]), send a GET request to that URL and delete session [: forwarding_url]. Otherwise, a GET request will be sent to root_url.