rack.git  about / heads / tags
a modular Ruby webserver interface
blob 3216d973e0daddfe0493588fed27d35c4f46a665 1265 bytes (raw)
$ git show no-unicorn:lib/rack/auth/digest/nonce.rb	# shows this blob on the CLI

 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 
# frozen_string_literal: true

require 'digest/md5'
require 'base64'

module Rack
  module Auth
    module Digest
      # Rack::Auth::Digest::Nonce is the default nonce generator for the
      # Rack::Auth::Digest::MD5 authentication handler.
      #
      # +private_key+ needs to set to a constant string.
      #
      # +time_limit+ can be optionally set to an integer (number of seconds),
      # to limit the validity of the generated nonces.

      class Nonce

        class << self
          attr_accessor :private_key, :time_limit
        end

        def self.parse(string)
          new(*Base64.decode64(string).split(' ', 2))
        end

        def initialize(timestamp = Time.now, given_digest = nil)
          @timestamp, @given_digest = timestamp.to_i, given_digest
        end

        def to_s
          Base64.encode64("#{@timestamp} #{digest}").strip
        end

        def digest
          ::Digest::MD5.hexdigest("#{@timestamp}:#{self.class.private_key}")
        end

        def valid?
          digest == @given_digest
        end

        def stale?
          !self.class.time_limit.nil? && (Time.now.to_i - @timestamp) > self.class.time_limit
        end

        def fresh?
          !stale?
        end

      end
    end
  end
end

git clone https://yhbt.net/rack.git