aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/active_storage/verified_key_with_expiration.rb
blob: 5cb07c6988ce8894a6ac9dd7fd7e419e8b1b2536 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ActiveStorage::VerifiedKeyWithExpiration
  class << self
    def encode(key, expires_in: nil)
      ActiveStorage.verifier.generate([ key, expires_at(expires_in) ])
    end

    def decode(encoded_key)
      key, expires_at = ActiveStorage.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