0
0
Ruby on Railsframework~30 mins

Session-based authentication in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Session-based Authentication in Rails
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Clearing the session user ID and current user variable logs the user out.