Module: BetterAuth::Plugins

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

Constant Summary collapse

API_KEY_ERROR_CODES =
{
  "INVALID_METADATA_TYPE" => "metadata must be an object or undefined",
  "REFILL_AMOUNT_AND_INTERVAL_REQUIRED" => "refillAmount is required when refillInterval is provided",
  "REFILL_INTERVAL_AND_AMOUNT_REQUIRED" => "refillInterval is required when refillAmount is provided",
  "USER_BANNED" => "User is banned",
  "UNAUTHORIZED_SESSION" => "Unauthorized or invalid session",
  "KEY_NOT_FOUND" => "API Key not found",
  "KEY_DISABLED" => "API Key is disabled",
  "KEY_EXPIRED" => "API Key has expired",
  "USAGE_EXCEEDED" => "API Key has reached its usage limit",
  "KEY_NOT_RECOVERABLE" => "API Key is not recoverable",
  "EXPIRES_IN_IS_TOO_SMALL" => "The expiresIn is smaller than the predefined minimum value.",
  "EXPIRES_IN_IS_TOO_LARGE" => "The expiresIn is larger than the predefined maximum value.",
  "INVALID_REMAINING" => "The remaining count is either too large or too small.",
  "INVALID_PREFIX_LENGTH" => "The prefix length is either too large or too small.",
  "INVALID_NAME_LENGTH" => "The name length is either too large or too small.",
  "METADATA_DISABLED" => "Metadata is disabled.",
  "RATE_LIMIT_EXCEEDED" => "Rate limit exceeded.",
  "NO_VALUES_TO_UPDATE" => "No values to update.",
  "KEY_DISABLED_EXPIRATION" => "Custom key expiration values are disabled.",
  "INVALID_API_KEY" => "Invalid API key.",
  "INVALID_USER_ID_FROM_API_KEY" => "The user id from the API key is invalid.",
  "INVALID_REFERENCE_ID_FROM_API_KEY" => "The reference id from the API key is invalid.",
  "INVALID_API_KEY_GETTER_RETURN_TYPE" => "API Key getter returned an invalid key type. Expected string.",
  "SERVER_ONLY_PROPERTY" => "The property you're trying to set can only be set from the server auth instance only.",
  "FAILED_TO_UPDATE_API_KEY" => "Failed to update API key",
  "NAME_REQUIRED" => "API Key name is required.",
  "ORGANIZATION_ID_REQUIRED" => "Organization ID is required for organization-owned API keys.",
  "USER_NOT_MEMBER_OF_ORGANIZATION" => "You are not a member of the organization that owns this API key.",
  "INSUFFICIENT_API_KEY_PERMISSIONS" => "You do not have permission to perform this action on organization API keys.",
  "NO_DEFAULT_API_KEY_CONFIGURATION_FOUND" => "No default api-key configuration found.",
  "ORGANIZATION_PLUGIN_REQUIRED" => "Organization plugin is required for organization-owned API keys. Please install and configure the organization plugin."
}.freeze
API_KEY_TABLE_NAME =
"apikey"

Class Method Summary collapse

Class Method Details

.api_key(configurations = {}, options = nil) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/better_auth/plugins/api_key.rb', line 50

def api_key(configurations = {}, options = nil)
  config = api_key_config(configurations, options)
  Plugin.new(
    id: "api-key",
    hooks: {
      before: [
        {
          matcher: ->(ctx) { !!api_key_session_header_config(ctx, config) },
          handler: ->(ctx) { api_key_session_hook(ctx, config) }
        }
      ]
    },
    endpoints: {
      create_api_key: api_key_create_endpoint(config),
      verify_api_key: api_key_verify_endpoint(config),
      get_api_key: api_key_get_endpoint(config),
      update_api_key: api_key_update_endpoint(config),
      delete_api_key: api_key_delete_endpoint(config),
      list_api_keys: api_key_list_endpoint(config),
      delete_all_expired_api_keys: api_key_delete_expired_endpoint(config)
    },
    schema: api_key_schema(config, config[:schema]),
    error_codes: API_KEY_ERROR_CODES,
    options: config
  )
end

.api_key_authorize_reference!(ctx, config, user_id, reference_id, action) ⇒ Object



413
414
415
416
417
418
419
# File 'lib/better_auth/plugins/api_key.rb', line 413

def api_key_authorize_reference!(ctx, config, user_id, reference_id, action)
  if config[:references].to_s == "organization"
    api_key_check_org_permission!(ctx, user_id, reference_id, action)
  elsif reference_id != user_id
    raise APIError.new("NOT_FOUND", message: API_KEY_ERROR_CODES["KEY_NOT_FOUND"])
  end
end

.api_key_background_tasks?(ctx) ⇒ Boolean

Returns:

  • (Boolean)


805
806
807
# File 'lib/better_auth/plugins/api_key.rb', line 805

def api_key_background_tasks?(ctx)
  ctx.context.options.advanced.dig(:background_tasks, :handler).respond_to?(:call)
end

.api_key_check_org_permission!(ctx, user_id, organization_id, action) ⇒ Object

Raises:

  • (APIError)


421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/better_auth/plugins/api_key.rb', line 421

def api_key_check_org_permission!(ctx, user_id, organization_id, action)
  org_plugin = ctx.context.options.plugins.find { |plugin| plugin.id == "organization" }
  raise APIError.new("INTERNAL_SERVER_ERROR", message: API_KEY_ERROR_CODES["ORGANIZATION_PLUGIN_REQUIRED"]) unless org_plugin

  member = ctx.context.adapter.find_one(model: "member", where: [{field: "userId", value: user_id}, {field: "organizationId", value: organization_id}])
  raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["USER_NOT_MEMBER_OF_ORGANIZATION"]) unless member

  permissions = {"apiKey" => [action]}
  return member if BetterAuth::Plugins.organization_permission?(ctx, org_plugin.options, member["role"], permissions, organization_id)

  raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["INSUFFICIENT_API_KEY_PERMISSIONS"])
end

.api_key_check_permissions!(record, required) ⇒ Object



820
821
822
823
824
825
826
827
828
829
830
# File 'lib/better_auth/plugins/api_key.rb', line 820

def api_key_check_permissions!(record, required)
  return if required.nil? || required == {}

  actual = api_key_decode_json(record["permissions"]) || {}
  required.each do |resource, actions|
    allowed = Array(actual[resource.to_s] || actual[resource.to_sym])
    unless Array(actions).all? { |action| allowed.include?(action) || allowed.include?(action.to_s) }
      raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["INVALID_API_KEY"])
    end
  end
end

.api_key_config(configurations, options = nil) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/better_auth/plugins/api_key.rb', line 77

def api_key_config(configurations, options = nil)
  if configurations.is_a?(Array)
    normalized_configs = configurations.map { |config| api_key_single_config(config) }
    if normalized_configs.any? { |config| config[:config_id].to_s.empty? }
      raise Error, "configId is required for each API key configuration in the api-key plugin."
    end
    config_ids = normalized_configs.map { |config| config[:config_id] }
    raise Error, "configId must be unique for each API key configuration in the api-key plugin." if config_ids.uniq.length != config_ids.length

    plugin_options = normalize_hash(options || {})
    default_config = normalized_configs.find { |config| api_key_default_config_id?(config[:config_id]) }
    default_config ||= normalized_configs.first
    default_config.merge(
      configurations: normalized_configs,
      schema: plugin_options[:schema] || default_config[:schema]
    )
  else
    config = api_key_single_config(configurations)
    config[:config_id] ||= "default"
    config.merge(configurations: [config])
  end
end

.api_key_config_id_matches?(record_config_id, expected_config_id) ⇒ Boolean

Returns:

  • (Boolean)


365
366
367
368
369
# File 'lib/better_auth/plugins/api_key.rb', line 365

def api_key_config_id_matches?(record_config_id, expected_config_id)
  return true if api_key_default_config_id?(record_config_id) && api_key_default_config_id?(expected_config_id)

  record_config_id.to_s == expected_config_id.to_s
end

.api_key_create_endpoint(config) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/better_auth/plugins/api_key.rb', line 178

def api_key_create_endpoint(config)
  Endpoint.new(path: "/api-key/create", method: "POST") do |ctx|
    body = normalize_hash(ctx.body)
    resolved_config = api_key_resolve_config(ctx.context, config, body[:config_id])
    session = Routes.current_session(ctx, allow_nil: true)
    if session && body[:user_id]
      raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["SERVER_ONLY_PROPERTY"])
    end

    reference_id = api_key_create_reference_id!(ctx, body, session, resolved_config)
    user_id = (resolved_config[:references].to_s == "organization") ? (session&.dig(:user, "id") || body[:user_id]) : reference_id

    api_key_validate_create_update!(body, resolved_config, create: true, client: !!session)
    key_prefix = body.key?(:prefix) ? body[:prefix] : resolved_config[:default_prefix]
    key = api_key_generate_key(resolved_config, key_prefix)
    now = Time.now
    hashed = api_key_hash(key, resolved_config)
    data = {
      configId: resolved_config[:config_id] || "default",
      name: body[:name],
      start: resolved_config[:starting_characters_config][:should_store] ? key[0, resolved_config[:starting_characters_config][:characters_length].to_i] : nil,
      prefix: key_prefix,
      key: hashed,
      userId: user_id,
      referenceId: reference_id,
      enabled: true,
      rateLimitEnabled: body.key?(:rate_limit_enabled) ? body[:rate_limit_enabled] : resolved_config[:rate_limit][:enabled],
      rateLimitTimeWindow: body[:rate_limit_time_window] || resolved_config[:rate_limit][:time_window],
      rateLimitMax: body[:rate_limit_max] || resolved_config[:rate_limit][:max_requests],
      requestCount: 0,
      remaining: body.key?(:remaining) ? body[:remaining] : (body[:refill_amount] || nil),
      refillAmount: body[:refill_amount],
      refillInterval: body[:refill_interval],
      lastRefillAt: now,
      expiresAt: api_key_expires_at(body, resolved_config),
      createdAt: now,
      updatedAt: now,
      permissions: api_key_encode_json(body[:permissions] || api_key_default_permissions(resolved_config, reference_id, ctx)),
      metadata: body.key?(:metadata) ? api_key_encode_json(body[:metadata]) : nil
    }
    record = api_key_store(ctx, data, resolved_config)
    api_key_public(record, reveal_key: key, include_key_field: true)
  end
end

.api_key_create_reference_id!(ctx, body, session, config) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/better_auth/plugins/api_key.rb', line 371

def api_key_create_reference_id!(ctx, body, session, config)
  if config[:references].to_s == "organization"
    organization_id = body[:organization_id]
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["ORGANIZATION_ID_REQUIRED"]) if organization_id.to_s.empty?

    user_id = session&.dig(:user, "id") || body[:user_id]
    raise APIError.new("UNAUTHORIZED", message: API_KEY_ERROR_CODES["UNAUTHORIZED_SESSION"]) if user_id.to_s.empty?

    api_key_check_org_permission!(ctx, user_id, organization_id, "create")
    organization_id
  elsif session && body[:user_id] && body[:user_id] != session[:user]["id"]
    raise APIError.new("UNAUTHORIZED", message: API_KEY_ERROR_CODES["UNAUTHORIZED_SESSION"])
  elsif session

    session[:user]["id"]
  else
    user_id = body[:user_id]
    raise APIError.new("UNAUTHORIZED", message: API_KEY_ERROR_CODES["UNAUTHORIZED_SESSION"]) if user_id.to_s.empty?

    user_id
  end
end

.api_key_decode_json(value) ⇒ Object



838
839
840
841
842
843
844
845
846
# File 'lib/better_auth/plugins/api_key.rb', line 838

def api_key_decode_json(value)
  return nil if value.nil?
  return value if value.is_a?(Hash)

  parsed = JSON.parse(value.to_s)
  parsed.is_a?(String) ? api_key_decode_json(parsed) : parsed
rescue JSON::ParserError
  nil
end

.api_key_default_config_id?(value) ⇒ Boolean

Returns:

  • (Boolean)


361
362
363
# File 'lib/better_auth/plugins/api_key.rb', line 361

def api_key_default_config_id?(value)
  value.nil? || value.to_s.empty? || value.to_s == "default"
end

.api_key_default_permissions(config, reference_id, ctx) ⇒ Object



406
407
408
409
410
411
# File 'lib/better_auth/plugins/api_key.rb', line 406

def api_key_default_permissions(config, reference_id, ctx)
  permissions = config.dig(:permissions, :default_permissions) || config[:default_permissions]
  return permissions.call(reference_id, ctx) if permissions.respond_to?(:call)

  permissions
end

.api_key_delete_endpoint(config) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/better_auth/plugins/api_key.rb', line 291

def api_key_delete_endpoint(config)
  Endpoint.new(path: "/api-key/delete", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    body = normalize_hash(ctx.body)
    resolved_config = api_key_resolve_config(ctx.context, config, body[:config_id])
    key_id = body[:key_id]
    record = api_key_find_by_id(ctx, key_id, resolved_config)
    raise APIError.new("NOT_FOUND", message: API_KEY_ERROR_CODES["KEY_NOT_FOUND"]) unless record && api_key_config_id_matches?(api_key_record_config_id(record), resolved_config[:config_id])

    record_config = api_key_resolve_config(ctx.context, config, api_key_record_config_id(record))
    api_key_authorize_reference!(ctx, record_config, session[:user]["id"], api_key_record_reference_id(record), "delete")

    api_key_delete_record(ctx, record, record_config)
    api_key_delete_expired(ctx.context, record_config)
    ctx.json({success: true})
  end
end

.api_key_delete_expired(context, config) ⇒ Object



713
714
715
716
717
718
719
720
721
722
# File 'lib/better_auth/plugins/api_key.rb', line 713

def api_key_delete_expired(context, config)
  return unless config[:storage] == "database" || config[:fallback_to_database]

  expired = context.adapter.find_many(model: API_KEY_TABLE_NAME).select do |record|
    record["expiresAt"] && record["expiresAt"] < Time.now
  end
  expired.each do |record|
    context.adapter.delete(model: API_KEY_TABLE_NAME, where: [{field: "id", value: record["id"]}])
  end
end

.api_key_delete_expired_endpoint(config) ⇒ Object



339
340
341
342
343
344
# File 'lib/better_auth/plugins/api_key.rb', line 339

def api_key_delete_expired_endpoint(config)
  Endpoint.new(path: "/api-key/delete-all-expired-api-keys", method: "POST") do |ctx|
    api_key_delete_expired(ctx.context, config)
    ctx.json({success: true})
  end
end

.api_key_delete_record(ctx, record, config) ⇒ Object



708
709
710
711
# File 'lib/better_auth/plugins/api_key.rb', line 708

def api_key_delete_record(ctx, record, config)
  ctx.context.adapter.delete(model: API_KEY_TABLE_NAME, where: [{field: "id", value: record["id"]}]) if config[:storage] == "database" || config[:fallback_to_database]
  api_key_storage_delete(ctx, record, config) if config[:storage] == "secondary-storage"
end

.api_key_deserialize_storage_record(record) ⇒ Object



772
773
774
775
776
777
# File 'lib/better_auth/plugins/api_key.rb', line 772

def api_key_deserialize_storage_record(record)
  %w[createdAt updatedAt expiresAt lastRefillAt lastRequest].each do |field|
    record[field] = api_key_normalize_time(record[field]) if record[field]
  end
  record
end

.api_key_encode_json(value) ⇒ Object



832
833
834
835
836
# File 'lib/better_auth/plugins/api_key.rb', line 832

def api_key_encode_json(value)
  return nil if value.nil?

  JSON.generate(value)
end

.api_key_error_code(error) ⇒ Object



446
447
448
# File 'lib/better_auth/plugins/api_key.rb', line 446

def api_key_error_code(error)
  API_KEY_ERROR_CODES.key(error.message) || error.code.to_s
end

.api_key_expires_at(body, config) ⇒ Object



632
633
634
635
636
637
638
# File 'lib/better_auth/plugins/api_key.rb', line 632

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

.api_key_find_by_hash(ctx, hashed, config) ⇒ Object



650
651
652
653
654
655
656
657
# File 'lib/better_auth/plugins/api_key.rb', line 650

def api_key_find_by_hash(ctx, hashed, config)
  if config[:storage] == "secondary-storage"
    record = api_key_storage_get(ctx, "api-key:#{hashed}", config) || api_key_storage_get(ctx, "api-key:key:#{hashed}", config)
    return record if record
    return nil unless config[:fallback_to_database]
  end
  ctx.context.adapter.find_one(model: API_KEY_TABLE_NAME, where: [{field: "key", value: hashed}])
end

.api_key_find_by_id(ctx, id, config) ⇒ Object



659
660
661
662
663
664
665
666
# File 'lib/better_auth/plugins/api_key.rb', line 659

def api_key_find_by_id(ctx, id, config)
  if config[:storage] == "secondary-storage"
    record = api_key_storage_get(ctx, "api-key:by-id:#{id}", config) || api_key_storage_get(ctx, "api-key:id:#{id}", config)
    return record if record
    return nil unless config[:fallback_to_database]
  end
  ctx.context.adapter.find_one(model: API_KEY_TABLE_NAME, where: [{field: "id", value: id}])
end

.api_key_generate_key(config, prefix) ⇒ Object



621
622
623
624
625
626
# File 'lib/better_auth/plugins/api_key.rb', line 621

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

  "#{prefix}#{Array.new(config[:default_key_length].to_i) { ("A".."Z").to_a[SecureRandom.random_number(26)] }.join}"
end

.api_key_get_endpoint(config) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/better_auth/plugins/api_key.rb', line 243

def api_key_get_endpoint(config)
  Endpoint.new(path: "/api-key/get", method: "GET") do |ctx|
    session = Routes.current_session(ctx)
    query = normalize_hash(ctx.query)
    resolved_config = api_key_resolve_config(ctx.context, config, query[:config_id])
    id = query[:id]
    record = api_key_find_by_id(ctx, id, resolved_config)
    raise APIError.new("NOT_FOUND", message: API_KEY_ERROR_CODES["KEY_NOT_FOUND"]) unless record && api_key_config_id_matches?(api_key_record_config_id(record), resolved_config[:config_id])

    record_config = api_key_resolve_config(ctx.context, config, api_key_record_config_id(record))
    api_key_authorize_reference!(ctx, record_config, session[:user]["id"], api_key_record_reference_id(record), "read")

    record = (ctx, record, record_config)
    api_key_delete_expired(ctx.context, record_config)
    ctx.json(api_key_public(record, include_key_field: false))
  end
end

.api_key_get_from_headers(ctx, config) ⇒ Object



809
810
811
812
813
814
815
816
817
818
# File 'lib/better_auth/plugins/api_key.rb', line 809

def api_key_get_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

.api_key_hash(key, config) ⇒ Object



628
629
630
# File 'lib/better_auth/plugins/api_key.rb', line 628

def api_key_hash(key, config)
  config[:disable_key_hashing] ? key.to_s : Crypto.sha256(key.to_s, encoding: :base64url)
end

.api_key_list_endpoint(config) ⇒ Object



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/better_auth/plugins/api_key.rb', line 309

def api_key_list_endpoint(config)
  Endpoint.new(path: "/api-key/list", method: "GET") do |ctx|
    session = Routes.current_session(ctx)
    query = normalize_hash(ctx.query)
    configs = query[:config_id] ? [api_key_resolve_config(ctx.context, config, query[:config_id])] : config.fetch(:configurations, [config])
    reference_id = query[:organization_id] || session[:user]["id"]
    expected_reference = query[:organization_id] ? "organization" : "user"
    api_key_check_org_permission!(ctx, session[:user]["id"], reference_id, "read") if query[:organization_id]
    records = configs.flat_map { |entry| api_key_list_for_reference(ctx, reference_id, entry) }.uniq { |record| record["id"] }
    records = records.select do |record|
      record_config = api_key_resolve_config(ctx.context, config, api_key_record_config_id(record))
      record_config[:references].to_s == expected_reference &&
        api_key_record_reference_id(record) == reference_id &&
        (!query[:config_id] || api_key_config_id_matches?(api_key_record_config_id(record), query[:config_id]))
    end
    total = records.length
    records = api_key_sort_records(records, query[:sort_by], query[:sort_direction])
    offset = query.key?(:offset) ? query[:offset].to_i : nil
    limit = query.key?(:limit) ? query[:limit].to_i : nil
    records = records.drop(offset) if offset
    records = records.first(limit) if limit
    records.each { |record| api_key_delete_expired(ctx.context, api_key_resolve_config(ctx.context, config, api_key_record_config_id(record))) }
    api_keys = records.map do |record|
      record_config = api_key_resolve_config(ctx.context, config, api_key_record_config_id(record))
      api_key_public((ctx, record, record_config), include_key_field: false)
    end
    ctx.json({apiKeys: api_keys, total: total, limit: limit, offset: offset})
  end
end

.api_key_list_for_reference(ctx, reference_id, config) ⇒ Object



672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/better_auth/plugins/api_key.rb', line 672

def api_key_list_for_reference(ctx, reference_id, config)
  if config[:storage] == "secondary-storage"
    begin
      storage = api_key_storage(config, ctx.context)
      ids = JSON.parse((storage&.get("api-key:by-ref:#{reference_id}") || storage&.get("api-key:user:#{reference_id}")).to_s)
      records = ids.filter_map { |id| api_key_find_by_id(ctx, id, config) }
      return records unless records.empty? && config[:fallback_to_database]
    rescue JSON::ParserError, NoMethodError
      return [] unless config[:fallback_to_database]
    end
  end
  records = ctx.context.adapter.find_many(model: API_KEY_TABLE_NAME, where: [{field: "referenceId", value: reference_id}])
  legacy = ctx.context.adapter.find_many(model: API_KEY_TABLE_NAME, where: [{field: "userId", value: reference_id}])
  (records + legacy).uniq { |record| record["id"] }
end

.api_key_list_for_user(ctx, user_id, config) ⇒ Object



668
669
670
# File 'lib/better_auth/plugins/api_key.rb', line 668

def api_key_list_for_user(ctx, user_id, config)
  api_key_list_for_reference(ctx, user_id, config)
end

.api_key_migrate_legacy_metadata(ctx, record, config) ⇒ Object



790
791
792
793
794
795
796
797
798
799
800
801
802
803
# File 'lib/better_auth/plugins/api_key.rb', line 790

def (ctx, record, config)
  parsed = api_key_decode_json(record["metadata"])
  return record unless parsed.is_a?(Hash)

  encoded = api_key_encode_json(parsed)
  return record.merge("metadata" => encoded) if record["metadata"] == encoded

  updated = record.merge("metadata" => encoded)
  if config[:storage] == "database" || config[:fallback_to_database]
    ctx.context.adapter.update(model: API_KEY_TABLE_NAME, where: [{field: "id", value: record["id"]}], update: {metadata: encoded})
  end
  api_key_storage_set(ctx, updated, config) if config[:storage] == "secondary-storage"
  updated
end

.api_key_next_request_count(record, now) ⇒ Object



552
553
554
555
556
557
558
559
560
# File 'lib/better_auth/plugins/api_key.rb', line 552

def api_key_next_request_count(record, now)
  last = api_key_normalize_time(record["lastRequest"])
  window = record["rateLimitTimeWindow"].to_i
  if last && window.positive? && ((now - last) * 1000) <= window
    record["requestCount"].to_i + 1
  else
    1
  end
end

.api_key_normalize_time(value) ⇒ Object



848
849
850
851
852
853
# File 'lib/better_auth/plugins/api_key.rb', line 848

def api_key_normalize_time(value)
  return value if value.is_a?(Time)
  return nil if value.nil?

  Time.parse(value.to_s)
end

.api_key_public(record, reveal_key: nil, include_key_field: false) ⇒ Object



779
780
781
782
783
784
785
786
787
788
# File 'lib/better_auth/plugins/api_key.rb', line 779

def api_key_public(record, reveal_key: nil, include_key_field: false)
  data = record.transform_keys(&:to_sym)
  output = data.except(:key)
  output[:configId] ||= api_key_record_config_id(record)
  output[:referenceId] ||= api_key_record_reference_id(record)
  output[:key] = reveal_key if include_key_field && reveal_key
  output[:metadata] = api_key_decode_json(data[:metadata])
  output[:permissions] = api_key_decode_json(data[:permissions])
  output
end

.api_key_rate_limited?(record, config, now) ⇒ Boolean

Returns:

  • (Boolean)


539
540
541
542
543
544
545
546
547
548
549
550
# File 'lib/better_auth/plugins/api_key.rb', line 539

def api_key_rate_limited?(record, config, now)
  return false if config[:rate_limit][:enabled] == false || record["rateLimitEnabled"] == false

  window = record["rateLimitTimeWindow"]
  max = record["rateLimitMax"]
  return false if window.nil? || max.nil?

  last = api_key_normalize_time(record["lastRequest"])
  return false unless last && ((now - last) * 1000) <= window.to_i

  record["requestCount"].to_i >= max.to_i
end

.api_key_record_config_id(record) ⇒ Object



402
403
404
# File 'lib/better_auth/plugins/api_key.rb', line 402

def api_key_record_config_id(record)
  record["configId"] || record[:configId] || "default"
end

.api_key_record_reference_id(record) ⇒ Object



394
395
396
# File 'lib/better_auth/plugins/api_key.rb', line 394

def api_key_record_reference_id(record)
  record["referenceId"] || record[:referenceId] || record["userId"] || record[:userId]
end

.api_key_record_user_id(record) ⇒ Object



398
399
400
# File 'lib/better_auth/plugins/api_key.rb', line 398

def api_key_record_user_id(record)
  record["userId"] || record[:userId] || (api_key_default_config_id?(record["configId"] || record[:configId]) && (record["referenceId"] || record[:referenceId]))
end

.api_key_resolve_config(context, config, config_id = nil) ⇒ Object



346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/better_auth/plugins/api_key.rb', line 346

def api_key_resolve_config(context, config, config_id = nil)
  configurations = config.fetch(:configurations, [config])
  return configurations.find { |entry| api_key_default_config_id?(entry[:config_id]) } || configurations.first if config_id.to_s.empty?

  configurations.find { |entry| entry[:config_id].to_s == config_id.to_s } ||
    begin
      default = configurations.find { |entry| api_key_default_config_id?(entry[:config_id]) }
      unless default
        context.logger.error(API_KEY_ERROR_CODES["NO_DEFAULT_API_KEY_CONFIGURATION_FOUND"]) if context.respond_to?(:logger) && context.logger.respond_to?(:error)
        raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["NO_DEFAULT_API_KEY_CONFIGURATION_FOUND"])
      end
      default
    end
end

.api_key_schema(config, custom_schema = nil) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/better_auth/plugins/api_key.rb', line 146

def api_key_schema(config, custom_schema = nil)
  base = {
    apikey: {
      fields: {
        configId: {type: "string", required: true, default_value: "default", index: true},
        name: {type: "string", required: false},
        start: {type: "string", required: false},
        prefix: {type: "string", required: false},
        key: {type: "string", required: true, index: true},
        referenceId: {type: "string", required: true, index: true},
        userId: {type: "string", required: false, index: true, references: {model: "user", field: "id", on_delete: "cascade"}},
        refillInterval: {type: "number", required: false},
        refillAmount: {type: "number", required: false},
        lastRefillAt: {type: "date", required: false},
        enabled: {type: "boolean", required: false, default_value: true},
        rateLimitEnabled: {type: "boolean", required: false, default_value: true},
        rateLimitTimeWindow: {type: "number", required: false, default_value: config[:rate_limit][:time_window]},
        rateLimitMax: {type: "number", required: false, default_value: config[:rate_limit][:max_requests]},
        requestCount: {type: "number", required: false, default_value: 0},
        remaining: {type: "number", required: false},
        lastRequest: {type: "date", required: false},
        expiresAt: {type: "date", required: false},
        createdAt: {type: "date", required: true},
        updatedAt: {type: "date", required: true},
        permissions: {type: "string", required: false},
        metadata: {type: "string", required: false}
      }
    }
  }
  deep_merge_hashes(base, normalize_hash(custom_schema || {}))
end

.api_key_session_header_config(ctx, config) ⇒ Object



450
451
452
453
454
# File 'lib/better_auth/plugins/api_key.rb', line 450

def api_key_session_header_config(ctx, config)
  config.fetch(:configurations, [config]).find do |entry|
    entry[:enable_session_for_api_keys] && api_key_get_from_headers(ctx, entry)
  end
end

.api_key_session_hook(ctx, config) ⇒ Object

Raises:

  • (APIError)


456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'lib/better_auth/plugins/api_key.rb', line 456

def api_key_session_hook(ctx, config)
  config = api_key_session_header_config(ctx, config) || config
  key = api_key_get_from_headers(ctx, config)
  unless key.is_a?(String)
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["INVALID_API_KEY_GETTER_RETURN_TYPE"])
  end
  raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["INVALID_API_KEY"]) if key.length < config[:default_key_length].to_i

  if config[:custom_api_key_validator].respond_to?(:call) && !config[:custom_api_key_validator].call({ctx: ctx, key: key})
    raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["INVALID_API_KEY"])
  end

  record = api_key_validate!(ctx, key, config)
  if config[:references].to_s != "user"
    raise APIError.new("UNAUTHORIZED", message: API_KEY_ERROR_CODES["INVALID_REFERENCE_ID_FROM_API_KEY"])
  end
  reference_id = api_key_record_reference_id(record)
  user = ctx.context.internal_adapter.find_user_by_id(reference_id)
  raise APIError.new("UNAUTHORIZED", message: API_KEY_ERROR_CODES["INVALID_REFERENCE_ID_FROM_API_KEY"]) unless user

  session = {
    user: user,
    session: {
      "id" => record["id"],
      "token" => key,
      "userId" => reference_id,
      "userAgent" => ctx.headers["user-agent"],
      "ipAddress" => ctx.headers["x-forwarded-for"],
      "createdAt" => Time.now,
      "updatedAt" => Time.now,
      "expiresAt" => record["expiresAt"] || (Time.now + ctx.context.options.session[:expires_in].to_i)
    }
  }
  ctx.context.set_current_session(session)
  nil
end

.api_key_single_config(options) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/better_auth/plugins/api_key.rb', line 100

def api_key_single_config(options)
  data = normalize_hash(options || {})
  rate_limit_options = data[:rate_limit] || {}
  starting_characters_options = data[:starting_characters_config] || {}
  {
    config_id: data[:config_id],
    api_key_headers: data[:api_key_headers] || "x-api-key",
    default_key_length: data[:default_key_length] || 64,
    default_prefix: data[:default_prefix],
    maximum_prefix_length: data.key?(:maximum_prefix_length) ? data[:maximum_prefix_length] : 32,
    minimum_prefix_length: data.key?(:minimum_prefix_length) ? data[:minimum_prefix_length] : 1,
    maximum_name_length: data.key?(:maximum_name_length) ? data[:maximum_name_length] : 32,
    minimum_name_length: data.key?(:minimum_name_length) ? data[:minimum_name_length] : 1,
    enable_metadata: data[:enable_metadata] || false,
    disable_key_hashing: data[:disable_key_hashing] || false,
    require_name: data[:require_name] || false,
    storage: data[:storage] || "database",
    rate_limit: {
      enabled: rate_limit_options.fetch(:enabled, true),
      time_window: rate_limit_options[:time_window] || 86_400_000,
      max_requests: rate_limit_options[:max_requests] || 10
    },
    key_expiration: {
      default_expires_in: data.dig(:key_expiration, :default_expires_in),
      disable_custom_expires_time: data.dig(:key_expiration, :disable_custom_expires_time) || false,
      max_expires_in: data.dig(:key_expiration, :max_expires_in) || 365,
      min_expires_in: data.dig(:key_expiration, :min_expires_in) || 1
    },
    starting_characters_config: {
      should_store: starting_characters_options.fetch(:should_store, true),
      characters_length: starting_characters_options[:characters_length] || 6
    },
    enable_session_for_api_keys: data[:enable_session_for_api_keys] || false,
    fallback_to_database: data[:fallback_to_database] || false,
    custom_storage: data[:custom_storage],
    custom_key_generator: data[:custom_key_generator],
    custom_api_key_getter: data[:custom_api_key_getter],
    custom_api_key_validator: data[:custom_api_key_validator],
    default_permissions: data[:default_permissions],
    permissions: data[:permissions] || {},
    references: data[:references] || "user",
    defer_updates: data[:defer_updates] || false,
    schema: data[:schema]
  }
end

.api_key_sort_records(records, sort_by, direction) ⇒ Object



434
435
436
437
438
439
440
441
442
443
444
# File 'lib/better_auth/plugins/api_key.rb', line 434

def api_key_sort_records(records, sort_by, direction)
  return records unless sort_by

  key = Schema.storage_key(sort_by)
  sorted = records.sort_by { |record| record[key] || record[key.to_sym] || "" }
  if direction.to_s.downcase == "desc"
    sorted.reverse
  else
    sorted
  end
end

.api_key_storage(config, context = nil) ⇒ Object



724
725
726
# File 'lib/better_auth/plugins/api_key.rb', line 724

def api_key_storage(config, context = nil)
  config[:custom_storage] || context&.options&.secondary_storage
end

.api_key_storage_delete(ctx, record, config) ⇒ Object



753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'lib/better_auth/plugins/api_key.rb', line 753

def api_key_storage_delete(ctx, record, config)
  storage = api_key_storage(config, ctx.context)
  return unless storage

  storage.delete("api-key:#{record["key"]}")
  storage.delete("api-key:by-id:#{record["id"]}")
  storage.delete("api-key:key:#{record["key"]}")
  storage.delete("api-key:id:#{record["id"]}")
  user_key = "api-key:by-ref:#{api_key_record_reference_id(record)}"
  ids = JSON.parse(storage.get(user_key).to_s).reject { |id| id == record["id"] }
  ids.empty? ? storage.delete(user_key) : storage.set(user_key, JSON.generate(ids))
rescue JSON::ParserError
  nil
end

.api_key_storage_get(ctx, key, config) ⇒ Object



728
729
730
731
732
733
# File 'lib/better_auth/plugins/api_key.rb', line 728

def api_key_storage_get(ctx, key, config)
  raw = api_key_storage(config, ctx.context)&.get(key)
  raw && api_key_deserialize_storage_record(JSON.parse(raw))
rescue JSON::ParserError
  nil
end

.api_key_storage_record(record) ⇒ Object



768
769
770
# File 'lib/better_auth/plugins/api_key.rb', line 768

def api_key_storage_record(record)
  record.transform_values { |value| value.is_a?(Time) ? value.iso8601 : value }
end

.api_key_storage_set(ctx, record, config) ⇒ Object



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'lib/better_auth/plugins/api_key.rb', line 735

def api_key_storage_set(ctx, record, config)
  storage = api_key_storage(config, ctx.context)
  return unless storage

  serialized = JSON.generate(api_key_storage_record(record))
  expires_at = api_key_normalize_time(record["expiresAt"])
  ttl = expires_at ? [(expires_at - Time.now).to_i, 0].max : nil
  reference_id = api_key_record_reference_id(record)
  storage.set("api-key:#{record["key"]}", serialized, ttl)
  storage.set("api-key:by-id:#{record["id"]}", serialized, ttl)
  user_key = "api-key:by-ref:#{reference_id}"
  ids = JSON.parse(storage.get(user_key).to_s)
  ids << record["id"] unless ids.include?(record["id"])
  storage.set(user_key, JSON.generate(ids))
rescue JSON::ParserError
  storage.set("api-key:by-ref:#{api_key_record_reference_id(record)}", JSON.generate([record["id"]]))
end

.api_key_store(ctx, data, config) ⇒ Object



640
641
642
643
644
645
646
647
648
# File 'lib/better_auth/plugins/api_key.rb', line 640

def api_key_store(ctx, data, config)
  record = nil
  if config[:storage] == "database" || config[:fallback_to_database]
    record = ctx.context.adapter.create(model: API_KEY_TABLE_NAME, data: data)
  end
  record ||= data.transform_keys { |key| Schema.storage_key(key) }.merge("id" => SecureRandom.hex(16))
  api_key_storage_set(ctx, record, config) if config[:storage] == "secondary-storage"
  record
end

.api_key_update_endpoint(config) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/better_auth/plugins/api_key.rb', line 261

def api_key_update_endpoint(config)
  Endpoint.new(path: "/api-key/update", method: "POST") do |ctx|
    body = normalize_hash(ctx.body)
    resolved_config = api_key_resolve_config(ctx.context, config, body[:config_id])
    session = Routes.current_session(ctx, allow_nil: true)
    user_id = session&.dig(:user, "id") || body[:user_id]
    raise APIError.new("UNAUTHORIZED", message: API_KEY_ERROR_CODES["UNAUTHORIZED_SESSION"]) unless user_id
    if session && body[:user_id] && body[:user_id] != session[:user]["id"]
      raise APIError.new("UNAUTHORIZED", message: API_KEY_ERROR_CODES["UNAUTHORIZED_SESSION"])
    end

    key_id = body[:key_id]
    record = api_key_find_by_id(ctx, key_id, resolved_config)
    raise APIError.new("NOT_FOUND", message: API_KEY_ERROR_CODES["KEY_NOT_FOUND"]) unless record
    raise APIError.new("NOT_FOUND", message: API_KEY_ERROR_CODES["KEY_NOT_FOUND"]) unless api_key_config_id_matches?(api_key_record_config_id(record), resolved_config[:config_id])

    record_config = api_key_resolve_config(ctx.context, config, api_key_record_config_id(record))
    api_key_authorize_reference!(ctx, record_config, user_id, api_key_record_reference_id(record), "update")

    api_key_validate_create_update!(body, record_config, create: false, client: !!session)
    update = api_key_update_payload(body, record_config)
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["NO_VALUES_TO_UPDATE"]) if update.empty?

    updated = api_key_update_record(ctx, record, update.merge(updatedAt: Time.now), record_config)
    updated = (ctx, updated, record_config)
    api_key_delete_expired(ctx.context, record_config)
    ctx.json(api_key_public(updated, include_key_field: false))
  end
end

.api_key_update_payload(body, _config) ⇒ Object



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/better_auth/plugins/api_key.rb', line 605

def api_key_update_payload(body, _config)
  update = {}
  update[:name] = body[:name] if body.key?(:name)
  update[:enabled] = body[:enabled] unless body[:enabled].nil?
  update[:remaining] = body[:remaining] if body.key?(:remaining)
  update[:refillAmount] = body[:refill_amount] if body.key?(:refill_amount)
  update[:refillInterval] = body[:refill_interval] if body.key?(:refill_interval)
  update[:rateLimitEnabled] = body[:rate_limit_enabled] if body.key?(:rate_limit_enabled)
  update[:rateLimitTimeWindow] = body[:rate_limit_time_window] if body.key?(:rate_limit_time_window)
  update[:rateLimitMax] = body[:rate_limit_max] if body.key?(:rate_limit_max)
  update[:expiresAt] = body[:expires_in].nil? ? nil : Time.now + body[:expires_in].to_i if body.key?(:expires_in)
  update[:metadata] = api_key_encode_json(body[:metadata]) if body.key?(:metadata)
  update[:permissions] = api_key_encode_json(body[:permissions]) if body.key?(:permissions)
  update
end

.api_key_update_record(ctx, record, update, config, defer: false) ⇒ Object



688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# File 'lib/better_auth/plugins/api_key.rb', line 688

def api_key_update_record(ctx, record, update, config, defer: false)
  performer = lambda do
    updated = nil
    if config[:storage] == "database" || config[:fallback_to_database]
      updated = ctx.context.adapter.update(model: API_KEY_TABLE_NAME, where: [{field: "id", value: record["id"]}], update: update)
    end
    updated ||= record.merge(update.transform_keys { |key| Schema.storage_key(key) })
    api_key_storage_set(ctx, updated, config) if config[:storage] == "secondary-storage"
    updated
  end

  if defer && config[:defer_updates] && api_key_background_tasks?(ctx)
    scheduled = record.merge(update.transform_keys { |key| Schema.storage_key(key) })
    ctx.context.run_in_background(performer)
    scheduled
  else
    performer.call
  end
end

.api_key_usage_update(record, config) ⇒ Object



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/better_auth/plugins/api_key.rb', line 514

def api_key_usage_update(record, config)
  now = Time.now
  update = {lastRequest: now, updatedAt: now}

  if api_key_rate_limited?(record, config, now)
    raise APIError.new("TOO_MANY_REQUESTS", message: API_KEY_ERROR_CODES["RATE_LIMIT_EXCEEDED"])
  end
  update[:requestCount] = api_key_next_request_count(record, now)

  remaining = record["remaining"]
  if !remaining.nil?
    if remaining.to_i <= 0 && record["refillAmount"] && record["refillInterval"]
      last_refill = api_key_normalize_time(record["lastRefillAt"] || record["lastRequest"] || record["createdAt"])
      if !last_refill || ((now - last_refill) * 1000) >= record["refillInterval"].to_i
        remaining = record["refillAmount"].to_i
        update[:lastRefillAt] = now
      end
    end
    raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["USAGE_EXCEEDED"]) if remaining.to_i <= 0

    update[:remaining] = remaining.to_i - 1
  end
  update
end

.api_key_validate!(ctx, key, config, permissions: nil) ⇒ Object

Raises:

  • (APIError)


493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/better_auth/plugins/api_key.rb', line 493

def api_key_validate!(ctx, key, config, permissions: nil)
  hashed = api_key_hash(key, config)
  record = api_key_find_by_hash(ctx, hashed, config)
  raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["INVALID_API_KEY"]) unless record
  raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["INVALID_API_KEY"]) unless api_key_config_id_matches?(api_key_record_config_id(record), config[:config_id])
  raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["KEY_DISABLED"]) if record["enabled"] == false
  if record["expiresAt"] && record["expiresAt"] <= Time.now
    api_key_delete_record(ctx, record, config)
    raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["KEY_EXPIRED"])
  end
  if record["remaining"].to_i <= 0 && !record["remaining"].nil? && record["refillAmount"].nil?
    api_key_delete_record(ctx, record, config)
    raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["USAGE_EXCEEDED"])
  end

  api_key_check_permissions!(record, permissions)
  update = api_key_usage_update(record, config)
  updated = api_key_update_record(ctx, record, update, config, defer: true)
  (ctx, updated || record.merge(update.transform_keys { |key_name| Schema.storage_key(key_name) }), config)
end

.api_key_validate_create_update!(body, config, create:, client:) ⇒ Object



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/better_auth/plugins/api_key.rb', line 562

def api_key_validate_create_update!(body, config, create:, client:)
  name = body[:name]
  if create && config[:require_name] && name.to_s.empty?
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["NAME_REQUIRED"])
  end
  if name && !name.to_s.length.between?(config[:minimum_name_length].to_i, config[:maximum_name_length].to_i)
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["INVALID_NAME_LENGTH"])
  end
  prefix = body[:prefix]
  if prefix && !prefix.to_s.length.between?(config[:minimum_prefix_length].to_i, config[:maximum_prefix_length].to_i)
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["INVALID_PREFIX_LENGTH"])
  end
  if prefix && !prefix.to_s.match?(/\A[a-zA-Z0-9_-]+\z/)
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["INVALID_PREFIX_LENGTH"])
  end
  if body.key?(:remaining) && !body[:remaining].nil?
    minimum = create ? 0 : 1
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["INVALID_REMAINING"]) if body[:remaining].to_i < minimum
  end
  if body.key?(:metadata)
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["METADATA_DISABLED"]) unless config[:enable_metadata]
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["INVALID_METADATA_TYPE"]) unless body[:metadata].nil? || body[:metadata].is_a?(Hash)
  end
  server_only_keys = %i[refill_amount refill_interval rate_limit_max rate_limit_time_window rate_limit_enabled remaining]
  server_only_keys << :permissions unless create
  if client && server_only_keys.any? { |key| body.key?(key) }
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["SERVER_ONLY_PROPERTY"])
  end
  if body[:refill_amount] && !body[:refill_interval]
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["REFILL_INTERVAL_AND_AMOUNT_REQUIRED"])
  end
  if body[:refill_interval] && !body[:refill_amount]
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["REFILL_AMOUNT_AND_INTERVAL_REQUIRED"])
  end
  if body.key?(:expires_in)
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["KEY_DISABLED_EXPIRATION"]) if config[:key_expiration][:disable_custom_expires_time]

    days = body[:expires_in].to_f / 86_400
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["EXPIRES_IN_IS_TOO_SMALL"]) if days < config[:key_expiration][:min_expires_in].to_f
    raise APIError.new("BAD_REQUEST", message: API_KEY_ERROR_CODES["EXPIRES_IN_IS_TOO_LARGE"]) if days > config[:key_expiration][:max_expires_in].to_f
  end
end

.api_key_verify_endpoint(config) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/better_auth/plugins/api_key.rb', line 223

def api_key_verify_endpoint(config)
  Endpoint.new(path: "/api-key/verify", method: "POST") do |ctx|
    body = normalize_hash(ctx.body)
    resolved_config = api_key_resolve_config(ctx.context, config, body[:config_id])
    key = body[:key] || api_key_get_from_headers(ctx, config)
    raise APIError.new("FORBIDDEN", message: API_KEY_ERROR_CODES["INVALID_API_KEY"], code: "INVALID_API_KEY") if key.to_s.empty?

    record = api_key_validate!(ctx, key, resolved_config, permissions: body[:permissions])
    record_config = api_key_resolve_config(ctx.context, config, api_key_record_config_id(record))
    api_key_delete_expired(ctx.context, record_config)
    ctx.json({valid: true, error: nil, key: api_key_public(record, include_key_field: false)})
  rescue APIError => error
    ctx.context.logger.error("Failed to validate API key: #{error.message}") if ctx.context.logger.respond_to?(:error)
    ctx.json({valid: false, error: {message: error.message, code: api_key_error_code(error)}, key: nil})
  rescue => error
    ctx.context.logger.error("Failed to validate API key: #{error.message}") if ctx.context.logger.respond_to?(:error)
    ctx.json({valid: false, error: {message: API_KEY_ERROR_CODES["INVALID_API_KEY"], code: "INVALID_API_KEY"}, key: nil})
  end
end