0

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?

Dmitry
  • 2,068
  • 2
  • 21
  • 30

2 Answers2

2

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'   
Arman H
  • 5,488
  • 10
  • 51
  • 76
  • Thanks for a great answer, but like @ch4nd4n said, it's not exactly the one I was looking for. – Dmitry Jun 15 '13 at 19:42
1

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.

ch4nd4n
  • 4,110
  • 2
  • 21
  • 43
  • Thanks mate! I ended up with a similar solution, only I just store session id in user's profile in DB (it's not a large app atm), and unless the current session has the id same as stored in db, I sign the user out. I store the session id on sign in. – Dmitry Jun 15 '13 at 19:43