Last active
February 10, 2017 15:34
-
-
Save cilim/a76b115650e021625c230291360e3ef1 to your computer and use it in GitHub Desktop.
How to add timeoutable to Stormpath in a Rails application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
include Stormpath::Rails::Controller | |
include Timeoutable | |
protect_from_forgery with: :exception | |
def show | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Each time a HTTP request is executed the
Timeoutable
module will check whether the user's session has timed out or not, based on thelast_request_at
timestamp that is stored in a cookie. If the user was idle for more thanEXPIRE_IN
he will get logged out and redirected to the login page. If the session has not expired then thelast_request_at
cookie will get updated with the new request time timestamp for the following request.