Dmitry
Dmitry

Reputation: 2138

How do I 'expire' sessions in Sinatra?

I sign in by storing their ID in session[user].

I don't want users to be signed in from one account on multiple devices. I want the site to expire other sessions for the user, when he signs in.

How do I do that?

Upvotes: 0

Views: 1028

Answers (2)

Arman H
Arman H

Reputation: 5618

The default session in Sinatra is just an alias for the underlying Rack session object. You need to use Rack::Session::Cookie directly instead of enable :sessions to set options like expiration (as described in the Sinatra FAQ: How Do I Use Sessions?):

# config.ru
use Rack::Session::Cookie, :key => 'rack.session',
                           :domain => 'foo.com',
                           :path => '/',
                           :expire_after => 2592000, # In seconds
                           :secret => 'change_me'   

Upvotes: 2

ch4nd4n
ch4nd4n

Reputation: 4197

You could use some caching store (like Memcached/Redis/Database) to keep record of logged in user as a key-value pair of userid to sessionid. In the code block where you create new session, check if key exists. If it does, expire the session id. Create new session and store the session id against the key.

Note I have not implemented exactly the same use case, but have done something similar using memcached. Using service like memcache to store this kind of information is much faster than using database.

Upvotes: 1

Related Questions