Module: Devise::Models::Expirable

Extended by:
ActiveSupport::Concern
Defined in:
lib/devise-security/models/expirable.rb

Overview

Deactivate the account after a configurable amount of time. To be able to tell, it tracks activity about your account with the following columns:

  • last_activity_at - A timestamp updated when the user requests a page (only signed in)

Options

:expire_after - Time interval to expire accounts after

Additions

Best used with two cron jobs. One for expiring accounts after inactivity, and another, that deletes accounts, which have expired for a given amount of time (for example 90 days).

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#active_for_authentication?bool

Overwrites active_for_authentication? from Devise::Models::Activatable for verifying whether a user is active to sign in or not. If the account is expired, it should never be allowed.

Returns:

  • (bool)

60
61
62
# File 'lib/devise-security/models/expirable.rb', line 60

def active_for_authentication?
  super && !self.expired?
end

#expire!(at = Time.now.utc) ⇒ Object

Note:

expired_at can be in the future as well

Expire an account. This is for cron jobs and manually expiring of accounts.

Examples:

User.expire!
User.expire! 1.week.from_now

50
51
52
53
# File 'lib/devise-security/models/expirable.rb', line 50

def expire!(at = Time.now.utc)
  self.expired_at = at
  save(validate: false)
end

#expired?bool

Tells if the account has expired

Returns:

  • (bool)

35
36
37
38
39
40
41
42
# File 'lib/devise-security/models/expirable.rb', line 35

def expired?
  # expired_at set (manually, via cron, etc.)
  return self.expired_at < Time.now.utc unless self.expired_at.nil?
  # if it is not set, check the last activity against configured expire_after time range
  return self.last_activity_at < self.class.expire_after.ago unless self.last_activity_at.nil?
  # if last_activity_at is nil as well, the user has to be 'fresh' and is therefore not expired
  false
end

#inactive_messageObject

The message sym, if #active_for_authentication? returns false. E.g. needed for i18n.


66
67
68
# File 'lib/devise-security/models/expirable.rb', line 66

def inactive_message
  !self.expired? ? super : :expired
end

#update_last_activity!Object

Updates last_activity_at, called from a Warden::Manager.after_set_user hook.


24
25
26
27
28
29
30
# File 'lib/devise-security/models/expirable.rb', line 24

def update_last_activity!
  if respond_to?(:update_column)
    self.update_column(:last_activity_at, Time.now.utc)
  elsif defined? Mongoid
    self.update_attribute(:last_activity_at, Time.now.utc)
  end
end