0
0
Ruby on Railsframework~10 mins

Session-based authentication in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to set the user ID in the session after login.

Ruby on Rails
session[:user_id] = [1]
Drag options to blanks, or click blank then click option'
Aparams[:id]
Bsession[:id]
Ccurrent_user
Duser.id
Attempts:
3 left
💡 Hint
Common Mistakes
Storing the whole user object in the session instead of just the ID.
Using params[:id] which may not be the logged-in user's ID.
2fill in blank
medium

Complete the code to find the current user from the session.

Ruby on Rails
def current_user
  @current_user ||= User.find_by(id: [1])
end
Drag options to blanks, or click blank then click option'
Asession[:user_id]
Bparams[:user_id]
Ccookies[:user_id]
Drequest.user_id
Attempts:
3 left
💡 Hint
Common Mistakes
Using params which only holds data from the current request.
Using cookies directly without session.
3fill in blank
hard

Fix the error in the logout method to clear the session.

Ruby on Rails
def logout
  [1]
end
Drag options to blanks, or click blank then click option'
Asession.delete(:user_id)
Bsession.clear(:user_id)
Csession.remove(:user_id)
Dsession[:user_id] = nil
Attempts:
3 left
💡 Hint
Common Mistakes
Using session.clear(:user_id) which is not a valid method.
Setting session[:user_id] to nil instead of deleting it.
4fill in blank
hard

Fill both blanks to check if a user is logged in and redirect if not.

Ruby on Rails
def require_login
  unless [1]
    redirect_to [2], alert: "Please log in"
  end
end
Drag options to blanks, or click blank then click option'
Acurrent_user
Bsession[:user_id]
Clogin_path
Droot_path
Attempts:
3 left
💡 Hint
Common Mistakes
Checking session[:user_id] directly instead of current_user.
Redirecting to root_path instead of login_path.
5fill in blank
hard

Fill all three blanks to create a session-based login method.

Ruby on Rails
def login
  user = User.find_by(email: params[:email])
  if user && user.authenticate([1])
    session[[2]] = user.[3]
    redirect_to dashboard_path
  else
    flash.now[:alert] = "Invalid email or password"
    render :new
  end
end
Drag options to blanks, or click blank then click option'
Aparams[:password]
B:user_id
Cid
Dparams[:email]
Attempts:
3 left
💡 Hint
Common Mistakes
Using params[:email] instead of params[:password] for authentication.
Storing the whole user object in the session.
Using wrong session key other than :user_id.