Module: BetterAuth::APIKey::Keys

Defined in:
lib/better_auth/api_key/keys.rb

Class Method Summary collapse

Class Method Details

.default_hasher(key) ⇒ Object



10
11
12
# File 'lib/better_auth/api_key/keys.rb', line 10

def default_hasher(key)
  BetterAuth::Crypto.sha256(key.to_s, encoding: :base64url)
end

.expires_at(body, config) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/better_auth/api_key/keys.rb', line 35

def expires_at(body, config)
  if body.key?(:expires_in)
    Time.now + body[:expires_in].to_i unless body[:expires_in].nil?
  elsif config[:key_expiration][:default_expires_in]
    Time.now + config[:key_expiration][:default_expires_in].to_i
  end
end

.from_headers(ctx, config) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/better_auth/api_key/keys.rb', line 43

def from_headers(ctx, config)
  getter = config[:custom_api_key_getter]
  return getter.call(ctx) if getter.respond_to?(:call)

  Array(config[:api_key_headers]).each do |header|
    value = ctx.headers[header.to_s.downcase]
    return value if value
  end
  nil
end

.generate(config, prefix) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/better_auth/api_key/keys.rb', line 14

def generate(config, prefix)
  generator = config[:custom_key_generator]
  return generator.call({length: config[:default_key_length], prefix: prefix}) if generator.respond_to?(:call)

  alphabet = [*("a".."z"), *("A".."Z")]
  "#{prefix}#{Array.new(config[:default_key_length].to_i) { alphabet[SecureRandom.random_number(alphabet.length)] }.join}"
end

.hash(key, config) ⇒ Object



22
23
24
# File 'lib/better_auth/api_key/keys.rb', line 22

def hash(key, config)
  config[:disable_key_hashing] ? key.to_s : default_hasher(key)
end

.normalize_body(raw) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/better_auth/api_key/keys.rb', line 26

def normalize_body(raw)
  body = BetterAuth::Plugins.normalize_hash(raw)
  return body unless raw.is_a?(Hash)

   = raw.key?(:metadata) ? :metadata : ("metadata" if raw.key?("metadata"))
  body[:metadata] = raw[] if 
  body
end