Session-based authentication helps websites remember who you are after you log in. It keeps you signed in while you browse.
Session-based authentication in Ruby on Rails
class SessionsController < ApplicationController def create user = User.find_by(email: params[:email]) if user&.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_path, notice: 'Logged in successfully' else flash.now[:alert] = 'Invalid email or password' render :new end end def destroy session.delete(:user_id) redirect_to root_path, notice: 'Logged out successfully' end end
Use session[:key] to store or access session data.
Sessions are stored on the server, and the browser keeps a cookie to identify the session.
session[:user_id] = user.id
session.delete(:user_id)
current_user = User.find_by(id: session[:user_id])
This example shows a simple session-based login system. The SessionsController handles logging in and out. The ApplicationController has a helper method to get the current user and a method to protect pages that need login.
class SessionsController < ApplicationController def new # Shows login form end def create user = User.find_by(email: params[:email]) if user&.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_path, notice: 'Logged in successfully' else flash.now[:alert] = 'Invalid email or password' render :new end end def destroy session.delete(:user_id) redirect_to root_path, notice: 'Logged out successfully' end end class ApplicationController < ActionController::Base helper_method :current_user def current_user @current_user ||= User.find_by(id: session[:user_id]) end def authenticate_user! redirect_to login_path, alert: 'Please log in' unless current_user end end
Sessions rely on cookies, so users must have cookies enabled in their browser.
Always use secure cookies (HTTPS) in production to protect session data.
Do not store sensitive data directly in the session; store only user IDs or tokens.
Session-based authentication remembers users by storing their ID in a server-side session.
Use session[:user_id] to track logged-in users.
Clear the session to log users out safely.
Practice
session[:user_id] typically store in a Rails application using session-based authentication?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
This key stores the unique identifier of the logged-in user to recognize them on subsequent requests.session[:user_id]holdsFinal Answer:
The ID of the currently logged-in user -> Option CQuick Check:
session[:user_id] = user ID [OK]
- Thinking session stores full user object
- Confusing user ID with password or email
- Assuming session is client-side storage
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 BQuick Check:
Any method removing user_id logs out user [OK]
- Only using session[:user_id] = nil and ignoring others
- Trying to clear session without removing user_id
- Confusing session.clear with resetting entire app
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
endWhat happens when the user enters correct email and password?
Solution
Step 1: Analyze authentication condition
The code checks if a user with the given email exists and if the password matches usingauthenticate.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 AQuick Check:
Correct login sets session[:user_id] and redirects [OK]
- Assuming user stays on login page after success
- Thinking session[:user_id] is not set on success
- Confusing render with redirect behavior
def logout session[:user] = nil redirect_to root_path end
Solution
Step 1: Check session key used for authentication
Rails session-based authentication typically usessession[:user_id]to track logged-in user.Step 2: Identify mismatch in session key
The code setssession[:user]to nil, which does not clear the actual user ID stored insession[:user_id].Final Answer:
Session key should be :user_id, not :user -> Option DQuick Check:
Correct session key is :user_id [OK]
- Using wrong session key name
- Assuming setting any session key to nil logs out user
- Confusing redirect_to with redirect_back
Solution
Step 1: Understand access control with before_action
Use a method to check ifsession[:user_id]exists before allowing access.Step 2: Identify correct redirect condition
Ifsession[:user_id]is missing, redirect to login page to block access.Final Answer:
Redirect to login unless session[:user_id] exists -> Option AQuick Check:
Access allowed only if session[:user_id] present [OK]
- Redirecting if session[:user_id] exists (wrong logic)
- Using wrong session key like :user
- Redirecting to wrong path on failure
Ready to prove it?
Pass the test and this pattern moves unknown
