Module: BetterAuth::APIKey::Routes::ListAPIKeys

Defined in:
lib/better_auth/api_key/routes/list_api_keys.rb

Constant Summary collapse

UPSTREAM_SOURCE =
"upstream/packages/api-key/src/routes/list-api-keys.ts"

Class Method Summary collapse

Class Method Details

.database_paginated_records(ctx, config, reference_id, expected_reference, query, limit, offset) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/better_auth/api_key/routes/list_api_keys.rb', line 79

def database_paginated_records(ctx, config, reference_id, expected_reference, query, limit, offset)
  return nil unless query[:config_id] && config
  return nil unless config[:storage].to_s == "database"
  return nil if BetterAuth::APIKey::Routes.default_config_id?(query[:config_id])
  return nil unless config[:references].to_s == expected_reference
  return nil if expected_reference == "user" && legacy_user_id_records?(ctx, reference_id, query[:config_id])

  where = [
    {field: "referenceId", value: reference_id},
    {field: "configId", value: query[:config_id]}
  ]
  sort_by = query[:sort_by] ? {field: query[:sort_by].to_s, direction: (query[:sort_direction] || "asc").to_s} : nil
  {
    records: ctx.context.adapter.find_many(
      model: BetterAuth::Plugins::API_KEY_TABLE_NAME,
      where: where,
      sort_by: sort_by,
      limit: limit,
      offset: offset
    ),
    total: ctx.context.adapter.count(model: BetterAuth::Plugins::API_KEY_TABLE_NAME, where: where)
  }
end

.endpoint(config) ⇒ Object



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
55
56
57
58
59
# File 'lib/better_auth/api_key/routes/list_api_keys.rb', line 11

def endpoint(config)
  BetterAuth::Endpoint.new(path: "/api-key/list", method: "GET", metadata: Routes.openapi_for(:list_api_keys)) do |ctx|
    session = BetterAuth::Routes.current_session(ctx)
    query = BetterAuth::Plugins.normalize_hash(ctx.query)
    BetterAuth::Plugins.api_key_validate_list_query!(query)
    configs = query[:config_id] ? [BetterAuth::Plugins.api_key_resolve_config(ctx.context, config, query[:config_id])] : storage_groups(config.fetch(:configurations, [config]))
    reference_id = query[:organization_id] || session[:user]["id"]
    expected_reference = query[:organization_id] ? "organization" : "user"
    BetterAuth::Plugins.api_key_check_org_permission!(ctx, session[:user]["id"], reference_id, "read") if query[:organization_id]
    offset = query.key?(:offset) ? query[:offset].to_i : nil
    limit = query.key?(:limit) ? query[:limit].to_i : nil
    pushed = database_paginated_records(ctx, configs.first, reference_id, expected_reference, query, limit, offset)
    if pushed
      records = pushed.fetch(:records)
      total = pushed.fetch(:total)
    else
      records = configs.flat_map { |entry| BetterAuth::Plugins.api_key_list_for_reference(ctx, reference_id, entry) }.uniq { |record| record["id"] }
      records = records.select do |record|
        record_config = BetterAuth::Plugins.api_key_resolve_config(ctx.context, config, BetterAuth::Plugins.api_key_record_config_id(record))
        record_config[:references].to_s == expected_reference &&
          BetterAuth::Plugins.api_key_record_reference_id(record) == reference_id &&
          (!query[:config_id] || BetterAuth::Plugins.api_key_config_id_matches?(BetterAuth::Plugins.api_key_record_config_id(record), query[:config_id]))
      end
      total = records.length
      records = BetterAuth::Plugins.api_key_sort_records(records, query[:sort_by], query[:sort_direction])
      records = records.drop(offset) if offset
      records = records.first(limit) if limit
    end
    cleanup_config = query[:config_id] ? configs.first : config
    BetterAuth::Plugins.api_key_delete_expired(ctx.context, cleanup_config)
    migration_records = records.select { |record| BetterAuth::APIKey::Adapter.(record) }
    if migration_records.any?
      BetterAuth::APIKey::Utils.run_background_task(
        ctx,
        "API key metadata migration",
        lambda do
          migration_records.each do |record|
            record_config = BetterAuth::Plugins.api_key_resolve_config(ctx.context, config, BetterAuth::Plugins.api_key_record_config_id(record))
            BetterAuth::APIKey::Adapter.(ctx, [record], record_config)
          end
        end
      )
    end
    api_keys = records.map do |record|
      BetterAuth::Plugins.api_key_public(record, include_key_field: false)
    end
    ctx.json({apiKeys: api_keys, total: total, limit: limit, offset: offset})
  end
end

.legacy_user_id_records?(ctx, reference_id, config_id) ⇒ Boolean

Returns:

  • (Boolean)


103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/better_auth/api_key/routes/list_api_keys.rb', line 103

def legacy_user_id_records?(ctx, reference_id, config_id)
  where = [
    {field: "userId", value: reference_id},
    {field: "configId", value: config_id}
  ]
  ctx.context.adapter.count(model: BetterAuth::Plugins::API_KEY_TABLE_NAME, where: where).positive?
rescue KeyError, NoMethodError
  false
rescue BetterAuth::Error => error
  raise unless error.message.include?("Field userId not found")

  false
end

.storage_groups(configurations) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/better_auth/api_key/routes/list_api_keys.rb', line 61

def storage_groups(configurations)
  seen = {}
  configurations.each_with_object([]) do |entry, groups|
    key = storage_identifier(entry)
    next if seen[key]

    seen[key] = true
    groups << entry
  end
end

.storage_identifier(config) ⇒ Object



72
73
74
75
76
77
# File 'lib/better_auth/api_key/routes/list_api_keys.rb', line 72

def storage_identifier(config)
  return "database" if config[:storage].to_s == "database"
  return "custom:#{config[:config_id] || "default"}" if config[:custom_storage]

  config[:fallback_to_database] ? "secondary-storage-with-fallback" : "secondary-storage"
end