Class: Negroni::TokenGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/negroni/token_generator.rb

Overview

Generates a secure token.

Instance Method Summary collapse

Constructor Details

#initialize(key_generator = nil, digest = 'SHA256', secret_key: nil) ⇒ TokenGenerator

Creates a new token generator.

version of an OpenSSL::Digest subclass. Default: ‘SHA256`.

Parameters:

  • key_generator (ActiveSupport::CachingKeyGenerator) (defaults to: nil)

    the generator

  • digest (String, Symbol) (defaults to: 'SHA256')

    The digest to use. Must be a stringified



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/negroni/token_generator.rb', line 13

def initialize(key_generator = nil, digest = 'SHA256', secret_key: nil)
  @key_generator = if secret_key
                     ActiveSupport::CachingKeyGenerator.new(
                       ActiveSupport::KeyGenerator.new(secret_key)
                     )
                   elsif key_generator
                     key_generator
                   else
                     raise ArgumentError, 'Unexpected arguments!'
                   end
  @digest = digest
end

Instance Method Details

#digest(_klass, column, value) ⇒ String

Digest a key.

Parameters:

  • _klass (Class)

    the class for which to digest the value.

  • column (String)

    the column name to digest.

  • value (#to_s)

    the value to digest.

Returns:

  • (String)

    the digested value.



33
34
35
36
# File 'lib/negroni/token_generator.rb', line 33

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

#generate(klass, column) ⇒ Object

Generate a key.

Parameters:

  • klass (Class)

    the class for which to generate the key.

  • column (String)

    the column name to generate a key for.



42
43
44
45
46
47
48
49
50
# File 'lib/negroni/token_generator.rb', line 42

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

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