ruby 26 lines · 6 steps

Idle session timeout in a Rails controller

A before_action logs the last-seen time on every request and signs users out after 30 minutes of inactivity.

Explained by highlit
1class ApplicationController < ActionController::Base
2 INACTIVITY_TIMEOUT = 30.minutes
3 
4 before_action :expire_stale_session
5 
6 private
7 
8 def expire_stale_session
9 return unless current_user
10 
11 last_seen = session[:last_seen_at]
12 
13 if last_seen && Time.zone.parse(last_seen) < INACTIVITY_TIMEOUT.ago
14 reset_session
15 redirect_to new_session_path, alert: "Your session expired due to inactivity."
16 return
17 end
18 
19 session[:last_seen_at] = Time.current.iso8601
20 end
21 
22 def current_user
23 @current_user ||= User.find_by(id: session[:user_id])
24 end
25 helper_method :current_user
26end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A sliding-window timeout works by rewriting the last-seen timestamp on every authenticated request.
  2. 2Storing timestamps as ISO8601 strings in the session keeps them serializable and unambiguous across time zones.
  3. 3reset_session clears the session server-side, so an expired user must sign in again before continuing.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Idle session timeout in a Rails controller — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code