Sha256: 49b2acfb5e32c81a6618ed278332a47205a5821e4baab8114d312f24be4de535

Contents?: true

Size: 758 Bytes

Versions: 6

Compression:

Stored size: 758 Bytes

Contents

require 'openssl'
require 'securerandom'

module Goma
  class TokenGenerator
    def initialize(key_generator, digest='SHA256')
      @key_generator = key_generator
      @digest = digest
    end

    def digest(column, value)
      value.present? && OpenSSL::HMAC.hexdigest(@digest, key_for(column), value.to_s)
    end

    def generate(klass, column)
      key = key_for(column)

      loop do
        raw = friendly_token
        enc = OpenSSL::HMAC.hexdigest(@digest, key, raw)
        break [raw, enc] unless klass.find_by(column => enc)
      end
    end

    def friendly_token
      SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz')
    end

    private
    def key_for(column)
      @key_generator.generate_key("Goma #{column}")
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
goma-0.0.1.rc3 lib/goma/token_generator.rb
goma-0.0.1.rc2 lib/goma/token_generator.rb
goma-0.0.1.rc1 lib/goma/token_generator.rb
goma-0.0.1.gamma lib/goma/token_generator.rb
goma-0.0.1.beta lib/goma/token_generator.rb
goma-0.0.1.alpha lib/goma/token_generator.rb