2 minutes before session timeout, warn the user and extend it with Devise | Rails 5

Viewed 1117

To auto logout user for being idle/inactive till 20 minutes. I have used Devise module :timeoutable and also set config.timeout_in = 20.minutes in devise configuration file. Which works perfectly fine.

Now when user have been inactive in the application for 18 minutes, would like to notify him

"You will be sign-out after 2 minutes due to your inactivity. If you wish to continue your session press Ok"

To achieve this I have added setInterval() function inside application.js which will make Ajax call each minute to check user's session (I have set expire time manually in session as below).

application_controller.rb:

class ApplicationController < ActionController::Base
  before_action :renew_user_session

  def renew_user_session
    session[:expires_at] = (Time.now + 20.minutes).to_s
  end
end

users_controller.rb:

class UsersController < ApplicationController
  skip_before_action :renew_user_session, only: :validate_user_session

  # this method is called in setInterval() through ajax
  def validate_user_session
    status = true
    if user_signed_in?
      status = (Time.parse(session[:expires_at]) - 2.minutes) > Time.now
    end
    respond_to do |format|
      format.json { render json: status }
    end
  end
end

but whenever I make Ajax call, it activate user. Is there anyway to check user's inactivity time? and notify before 2 minutes? or any alternate solution to achieve this?

0 Answers
Related