📖 Scenario: You are building a simple web app where users can log in and log out securely. The app uses session-based authentication to remember who is logged in during their visit.
🎯 Goal: Create a basic Rails setup that stores user login information in a session and allows users to log in and log out.
📋 What You'll Learn
Create a User model with a fixed username and password
Add a controller variable to hold the current user session
Implement a login method that sets the session user ID
Implement a logout method that clears the session user ID
💡 Why This Matters
🌍 Real World
Session-based authentication is used in many web apps to keep users logged in securely during their visit.
💼 Career
Understanding session management is essential for backend and full-stack developers working with Rails or similar frameworks.
Progress0 / 4 steps
1
Create a User model with fixed credentials
Create a User model class with a class method authenticate that accepts username and password. It should return a user object with id 1 if the username is "admin" and password is "secret", otherwise return nil.
Ruby on Rails
Hint
Think of authenticate as a gatekeeper that only lets the right username and password through.
2
Add a controller variable to hold current user session
In a controller class SessionsController, create an instance variable @current_user initialized to nil to hold the logged-in user.
Ruby on Rails
Hint
Think of @current_user as a placeholder for who is logged in right now.
3
Implement login method to set session user ID
In SessionsController, add a method login that takes username and password. Use User.authenticate to check credentials. If valid, set @current_user to the user and set session[:user_id] to @current_user.id.
Ruby on Rails
Hint
Use the authenticate method to check credentials and store the user ID in the session hash.
4
Implement logout method to clear session user ID
In SessionsController, add a method logout that sets @current_user to nil and deletes session[:user_id].
Ruby on Rails
Hint
Clearing the session user ID and current user variable logs the user out.
Practice
(1/5)
1. What does session[:user_id] typically store in a Rails application using session-based authentication?
easy
A. The user's password
B. The user's email address
C. The ID of the currently logged-in user
D. The entire user object
Solution
Step 1: Understand session usage in Rails
Rails uses the session hash to store small pieces of data between requests, commonly the user ID for authentication.
Step 2: Identify what session[:user_id] holds
This key stores the unique identifier of the logged-in user to recognize them on subsequent requests.
Final Answer:
The ID of the currently logged-in user -> Option C
Quick Check:
session[:user_id] = user ID [OK]
Hint: Remember session stores user ID, not full user data [OK]
Common Mistakes:
Thinking session stores full user object
Confusing user ID with password or email
Assuming session is client-side storage
2. Which of the following is the correct way to log out a user by clearing the session in a Rails controller?
easy
A. session.clear
B. All of the above
C. session[:user_id] = nil
D. session.delete(:user_id)
Solution
Step 1: Review methods to clear session data
In Rails, you can remove session data by clearing all keys, deleting a specific key, or setting a key to nil.
Step 2: Confirm all options effectively log out user
All three methods remove the user ID from session, effectively logging out the user.
Final Answer:
All of the above -> Option B
Quick Check:
Any method removing user_id logs out user [OK]
Hint: Any method removing session[:user_id] logs out user [OK]
Common Mistakes:
Only using session[:user_id] = nil and ignoring others
Trying to clear session without removing user_id
Confusing session.clear with resetting entire app
3. Given this Rails controller code snippet:
def create
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
session[:user_id] = user.id
redirect_to dashboard_path
else
render :new
end
end
What happens when the user enters correct email and password?
medium
A. User ID is saved in session and redirected to dashboard
B. User is redirected to login page again
C. Session is cleared and user stays on login page
D. An error is raised because session[:user_id] is not set
Solution
Step 1: Analyze authentication condition
The code checks if a user with the given email exists and if the password matches using authenticate.
Step 2: Understand session assignment and redirect
If authentication passes, it stores the user's ID in session and redirects to the dashboard.
Final Answer:
User ID is saved in session and redirected to dashboard -> Option A
Quick Check:
Correct login sets session[:user_id] and redirects [OK]
Hint: Correct login sets session[:user_id] and redirects [OK]
Common Mistakes:
Assuming user stays on login page after success
Thinking session[:user_id] is not set on success
Confusing render with redirect behavior
4. Identify the error in this logout action:
def logout
session[:user] = nil
redirect_to root_path
end
medium
A. No error, this code works fine
B. redirect_to should be redirect_back
C. session[:user] = nil does not clear session
D. Session key should be :user_id, not :user
Solution
Step 1: Check session key used for authentication
Rails session-based authentication typically uses session[:user_id] to track logged-in user.
Step 2: Identify mismatch in session key
The code sets session[:user] to nil, which does not clear the actual user ID stored in session[:user_id].
Final Answer:
Session key should be :user_id, not :user -> Option D
Quick Check:
Correct session key is :user_id [OK]
Hint: Use session[:user_id] to clear login, not session[:user] [OK]
Common Mistakes:
Using wrong session key name
Assuming setting any session key to nil logs out user
Confusing redirect_to with redirect_back
5. You want to restrict access to a controller action so only logged-in users can see it. Which code snippet correctly checks session-based authentication before allowing access?
hard
A. before_action :require_login
def require_login
redirect_to login_path unless session[:user_id]
end
B. before_action :require_login
def require_login
redirect_to login_path if session[:user_id]
end
C. before_action :require_login
def require_login
redirect_to root_path unless session[:user_id]
end
D. before_action :require_login
def require_login
redirect_to login_path unless session[:user]
end
Solution
Step 1: Understand access control with before_action
Use a method to check if session[:user_id] exists before allowing access.
Step 2: Identify correct redirect condition
If session[:user_id] is missing, redirect to login page to block access.
Final Answer:
Redirect to login unless session[:user_id] exists -> Option A
Quick Check:
Access allowed only if session[:user_id] present [OK]
Hint: Redirect unless session[:user_id] exists to protect pages [OK]
Common Mistakes:
Redirecting if session[:user_id] exists (wrong logic)
Using wrong session key like :user
Redirecting to wrong path on failure
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.