aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_vault/verified_key_with_expiration.rb
blob: 95d4993ff057aed4f46b3eac4c56de45403049b0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ActiveVault::VerifiedKeyWithExpiration
  class_attribute :verifier, default: defined?(Rails) ? Rails.application.message_verifier('ActiveVault') : nil

  class << self
    def encode(key, expires_in: nil)
      verifier.generate([ key, expires_at(expires_in) ])
    end

    def decode(encoded_key)
      key, expires_at = verifier.verified(encoded_key)

      key if key && fresh?(expires_at)
    end

    private
      def expires_at(expires_in)
        expires_in ? Time.now.utc.advance(seconds: expires_in) : nil
      end

      def fresh?(expires_at)
        expires_at.nil? || Time.now.utc < expires_at
      end
  end
end