main
1# frozen_string_literal: true
2
3class UserSession < ApplicationRecord
4 IDLE_TIMEOUT = 30.minutes
5 audited associated_with: :user, except: [:key, :accessed_at]
6 has_secure_token :key
7 belongs_to :user
8
9 scope :active, -> { where.not(id: revoked).where.not(id: expired) }
10 scope :revoked, -> { where.not(revoked_at: nil) }
11 scope :expired, -> { where(id: idle_timeout).or(where(id: absolute_timeout)) }
12 scope :idle_timeout, -> { where("accessed_at < ?", IDLE_TIMEOUT.ago) }
13 scope :absolute_timeout, -> { where('created_at < ?', 24.hours.ago) }
14
15 def self.authenticate(key)
16 return if key.blank?
17
18 active.find_by(key: key)
19 end
20
21 def browser
22 @browser ||= ::Browser.new(user_agent, accept_language: "en-us")
23 end
24
25 def revoke!
26 update!(revoked_at: Time.current)
27 end
28
29 def sudo?
30 sudo_enabled_at.present? && sudo_enabled_at > 1.hour.ago
31 end
32
33 def sudo!
34 update!(sudo_enabled_at: Time.current)
35 end
36
37 def access(request)
38 update(
39 accessed_at: Time.current,
40 ip: request.ip,
41 user_agent: request.user_agent,
42 )
43 key
44 end
45end