Skip to content

Instantly share code, notes, and snippets.

@cilim
Last active February 10, 2017 15:34
Show Gist options
  • Save cilim/a76b115650e021625c230291360e3ef1 to your computer and use it in GitHub Desktop.
Save cilim/a76b115650e021625c230291360e3ef1 to your computer and use it in GitHub Desktop.
How to add timeoutable to Stormpath in a Rails application
class ApplicationController < ActionController::Base
include Stormpath::Rails::Controller
include Timeoutable
protect_from_forgery with: :exception
def show
end
end
module Timeoutable
extend ActiveSupport::Concern
EXPIRE_IN = 10.minutes
included do
before_action :logout_idle_users, if: :signed_in?
end
def logout_idle_users
if session_expired?
reset_session
delete_cookies
redirect_to new_login_path, notice: 'Your session has expired. Please log in!'
else
set_last_request_at
end
end
private
def session_expired?
current_time - last_request_at > EXPIRE_IN.to_i
end
def delete_cookies
cookies.delete(access_token_cookie_name)
cookies.delete(refresh_token_cookie_name)
cookies.delete(:last_request_at)
end
def current_time
Time.now.to_i
end
def last_request_at
(cookies[:last_request_at] || set_last_request_at).to_i
end
def set_last_request_at
cookies[:last_request_at] = current_time
end
def access_token_cookie_name
Stormpath::Rails.config.web.access_token_cookie.name
end
def refresh_token_cookie_name
Stormpath::Rails.config.web.refresh_token_cookie.name
end
end
@cilim
Copy link
Author

cilim commented Feb 10, 2017

Each time a HTTP request is executed the Timeoutable module will check whether the user's session has timed out or not, based on the last_request_at timestamp that is stored in a cookie. If the user was idle for more than EXPIRE_IN he will get logged out and redirected to the login page. If the session has not expired then the last_request_at cookie will get updated with the new request time timestamp for the following request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment