0
0
Ruby on Railsframework~30 mins

Remember me functionality in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Remember Me Functionality
📖 Scenario: You are building a simple login system for a website. Users can choose to stay logged in even after closing their browser by selecting a "Remember me" checkbox.This feature uses cookies to keep users logged in automatically on their next visit.
🎯 Goal: Create a basic "Remember me" feature in a Rails app that sets a persistent cookie when the user logs in and uses it to authenticate the user automatically on future visits.
📋 What You'll Learn
Create a method to generate a remember token and save its digest in the user model
Add a controller variable to hold the remember token
Implement the logic to set and delete the remember cookie
Add the final helper methods to check and forget the user session
💡 Why This Matters
🌍 Real World
Remember me functionality is common on websites to improve user experience by keeping users logged in between visits without re-entering credentials.
💼 Career
Understanding how to implement secure persistent login is important for web developers working on authentication systems and user session management.
Progress0 / 4 steps
1
Add remember token and digest to User model
In the User model, add a method called remember that generates a new token using SecureRandom.urlsafe_base64 and saves its digest using BCrypt::Password.create in an attribute called remember_digest.
Ruby on Rails
Need a hint?

Use attr_accessor :remember_token to create a temporary token attribute.

Use SecureRandom.urlsafe_base64 to generate the token.

2
Add remember token variable in Sessions controller
In the SessionsController, create an instance variable @remember_token and assign it a new token generated by SecureRandom.urlsafe_base64.
Ruby on Rails
Need a hint?

Assign @remember_token inside the create action.

3
Set and delete remember cookies in Sessions helper
In the SessionsHelper module, write two methods: remember(user) that sets a permanent signed cookie :user_id and a permanent cookie :remember_token with the user's remember token, and forget(user) that deletes these cookies.
Ruby on Rails
Need a hint?

Use cookies.permanent.signed for secure user ID storage.

Use cookies.permanent for the token.

4
Add helper methods to check and forget user session
In the SessionsHelper, add a method current_user that returns the logged-in user by checking the signed :user_id cookie and authenticating the :remember_token. Also add a method logged_in? that returns true if current_user is not nil.
Ruby on Rails
Need a hint?

Use cookies.signed[:user_id] to get the user ID.

Use BCrypt::Password.new(...).is_password?(...) to verify the token.