I am implementing a session in my Rails Application, and I'm using DeviseTokenAuth gem.
I want to implement a scenario that If a user does not send a request from the Front-end in 15 minutes, then the session should expire; The session is valid for 15 minutes. However, if a user is sending requests continuously, the session time should be extended for the next 15 minutes. I am sharing my DeviseTokenAuth configuration code.
DeviseTokenAuth.setup do |config|
config.change_headers_on_each_request = true
config.token_lifespan = 15.minutes
config.token_cost = Rails.env.test? ? 4 : 10
config.batch_request_buffer_throttle = 30.seconds
end
Please let me know, If I am doing anything wrong
OK, so you've set token_lifespan to 15 minutes (which DeviseTokenAuth understands as '15 minutes since last login'), but you actually want it to be last_accessed_at + 15.minutes. This isn't really what DeviseTokenAuth is designed to do, so you're going to need to write your own handlers for this.
You probably need a before_action that runs every time a request is received, which checks how long it's been since the last request, and invalidates the token if it's been more than 15 minutes. And you'll need a matching after_action filter that stores the time the user last accessed the application in the database (in a field like last_accessed_at similar to the automatic created_at field).
You can create a separate column, last_accessed_at which should be the DateTime field in the user's table.
Then, add the below snippet in the app/controllers/application_controller.rb
before_action :authenticate_user!, :validate_last_accessed
def validate_last_accessed
if (current_user.last_accessed_at + 14.minutes) < DateTime.now
current_user.tokens = {}
current_user.save
render json: {success: false, message: "your message in here"}
else
current_user.update(last_accessed_at: DateTime.now)
end
end
There is no need for setting up token expiry to 15 minutes, you can even set it up to any number of days/weeks. The tokens will be cleared if the user is not accessing the application within the given time frame which is 15 minutes in this case.
PRO TIP: For the purpose of this feature, for every request you have to hit the database for updating the record. I would recommend you to use the cache database such as redis to store/update the user's last accessed time.
Another Solution: You can send the current datetime in every controller response, let the frontend takes care of the timeframe.