简体   繁体   中英

Limit sessions number concurrent per account user devise, rails 4

Using Rails 4.0 and ruby 2.1.0

I'm working on a project that will be subscription based and the accounts need to have a limit of concurrent sessions per user. For example, normal user 1 concurrent session per account, medium user - 3 concurrent sessions per account and premium user 10 concurrent sessions per account.

I have checked every page of google, stackoverflow, differents gems like devise:timeoutable or devise_session_limit gem. I have tried with a field called connections which is 1, 3 or 10 depending on user. If user login, decrement -1 the connections field, if user logout then increment +1 connectios field. The thing or problem is when the user keep open the session and leave, then never will increment +1.

Any suggestions?? I am working on this task almost 3 days and I cannot get it.

Thanks in advance!

You can hook into devise and as long as you have the :timeoutable module you can check that a user has been timed out and run whatever code you like. See this warden hook for reference: https://github.com/plataformatec/devise/blob/master/lib/devise/hooks/timeoutable.rb

The important part of that code is the check for record.timedout? . If that's true, run your connections increment code.

To be specific, write a config/initializers/connections_updater.rb file with this (similar to above linked code it is a warden hook):

Warden::Manager.after_set_user do |record, warden, options|
  scope = options[:scope]
  env   = warden.request.env

  if record && record.respond_to?(:timedout?) && warden.authenticated?(scope) && options[:store] != false
    last_request_at = warden.session(scope)['last_request_at']

    if last_request_at.is_a? Integer
      last_request_at = Time.at(last_request_at).utc
    elsif last_request_at.is_a? String
      last_request_at = Time.parse(last_request_at)
    end

    proxy = Devise::Hooks::Proxy.new(warden)

    if record.timedout?(last_request_at) && !env['devise.skip_timeout']
      # write this method to do what you need when the session times out
      record.increment_connections_count! # Note: record is the user model

      Devise.sign_out_all_scopes ? proxy.sign_out : proxy.sign_out(scope)
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM