Consider a typical Rails login controller action that authenticates a user and sets a session. What is the expected behavior immediately after a successful login?
def create user = User.find_by(email: params[:email]) if user&.authenticate(params[:password]) session[:user_id] = user.id redirect_to dashboard_path else flash.now[:alert] = "Invalid email or password" render :new end end
Think about what happens when login is successful: where is the user ID stored and what does the app do next?
On successful login, Rails stores the user ID in the session hash and redirects the user to a protected page like the dashboard. This keeps the user logged in across requests.
Given this logout action in a Rails controller, what will be the state of session[:user_id] after it runs?
def destroy
session.delete(:user_id)
redirect_to root_path
endDeleting a key from the session removes it. What does that mean when you try to read it later?
Calling session.delete(:user_id) removes the key from the session hash, so accessing session[:user_id] returns nil.
Which option contains the correct syntax for authenticating a user in Rails?
def login user = User.find_by(email: params[:email]) if user.authenticate(params[:password]) session[:user_id] = user.id redirect_to root_path else render :new end end
Consider what happens if user is nil. How to safely call authenticate?
Using the safe navigation operator &. prevents calling authenticate on nil, avoiding a NoMethodError.
Given this logout method, why does the user remain logged in after logout?
def logout
session[:user_id] == nil
redirect_to root_path
endLook carefully at the line that tries to clear the session key. Is it doing what you expect?
The code uses == which compares values but does not assign. To clear the session key, use = nil or session.delete(:user_id).
In Rails, calling reset_session during logout is recommended. Why is this important?
Think about what happens if an attacker steals a session ID before logout.
Resetting the session creates a new session ID, preventing attackers from reusing an old session ID (session fixation). This improves security.