Skip to content

Instantly share code, notes, and snippets.

@dpneumo
Created Nov 11, 2018
Embed
What would you like to do?
Session setup Rails 5.2

Session in Rails 5.2

  • Expiration:

    • Absolute age
      • In config/initializers/session_store.rb:
      Rails.application.config.session_store  :cookie_store,
        key: '_cirrus_session',
        expire_after: 1.days,
        ...
      
    • At Logout
      • In app/helpers/sessions_helper.rb:
      def log_in(user)
        session[:user_id] = user.id
        ...
      end
      
      def log_out
        session.delete(:user_id)
        ...
      end
      
    • Inactivity period
      • In app/helpers/sessions_helper.rb:
      ExpireSessions = Rails.env.production? || Rails.env.development?
      MaxInactivity = 10.minutes
      
      def log_in(user)
        ...
        session[:last_action] = Time.now
      end
      
      def logged_in?
        expire_stale_session
        current_user.nil? ? false : reset_session_timer
      end
      
      private
        def reset_session_timer
          session[:last_action] = Time.now
        end
      
        def expire_stale_session
          if (session_timer > MaxInactivity) && ExpireSessions
            flash[:danger] = "Session timed out after #{MaxInactivity} seconds"
            log_out
          end
        end
      
        def session_timer
          session[:last_action] ? Time.now - session[:last_action].to_time : 0
        end
      
      • In app/controllers/application_controller.rb
      class ApplicationController < ActionController::Base
        include SessionsHelper
        before_action :require_login
      
        private
          def require_login
            unless logged_in?
              flash[:error] = "You must be logged in to access this section"
              redirect_to login_url # halts request cycle
            end
          end
      end
      
      • In app/controllers/sessions_controller.rb
      class SessionsController < ApplicationController
        skip_before_action :require_login, only: [:new, :create]
      
        def new; ...; end
      
        def create; ...; end
        ...
      end
      
      • In app/controllers/users_controller.rb
      class UsersController < ApplicationController
        skip_before_action :require_login, only: [:new, :create]
        ...
      end
      
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment