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
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.