summaryrefslogtreecommitdiff
path: root/app/models/session.rb
blob: 006e847d037405b379cada2e9a20027102208a82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Session < ActiveRecord::Base
  belongs_to :user
  before_create :create_key

  def access(request)
    self.ip_address = request.remote_ip
    if save
      {
        value: self.key,
        httponly: true,
        secure: Rails.env.production? || Rails.env.staging?,
        expires: 2.weeks.from_now
      }
    else
      raise "heck"
    end
  end

  def revoke!
    update_attribute(:revoked_at, Time.now.utc)
  end

  class << self
    def active
      where(revoked_at: nil)
    end

    def authenticate!(session_key)
      active.find_by!(key: session_key)
    end
  end

  private

  def create_key
    self.key = SecureRandom.uuid
  end
end