Current section
Files
Jump to
Current section
Files
lib/coffrify/resources/api_keys.ex
defmodule Coffrify.Resources.ApiKeys do
@moduledoc """
API keys — `cof_*` strings used to authenticate Coffrify API requests.
"""
alias Coffrify
@doc "List every API key in the workspace."
@spec list(Coffrify.t()) :: {:ok, map()} | {:error, Exception.t()}
def list(client), do: Coffrify.request(client, :get, "/api-keys")
@doc """
Create a new API key. The returned `key` is shown ONCE — store it
securely. Ultra plan required for `allowed_ips`, `expires_in_days`,
`max_uses`.
"""
@spec create(Coffrify.t(), map() | keyword()) :: {:ok, map()} | {:error, Exception.t()}
def create(client, opts), do: Coffrify.request(client, :post, "/api-keys", Map.new(opts))
@doc "Patch an API key (name, description, is_active, allowed_ips)."
@spec update(Coffrify.t(), String.t(), map()) :: {:ok, map()} | {:error, Exception.t()}
def update(client, id, updates),
do: Coffrify.request(client, :patch, "/api-keys/#{URI.encode(id)}", updates)
@doc "Revoke an API key."
@spec revoke(Coffrify.t(), String.t(), keyword()) :: {:ok, map()} | {:error, Exception.t()}
def revoke(client, id, opts \\ []) do
body =
case Keyword.get(opts, :reason) do
nil -> nil
reason -> %{reason: reason}
end
Coffrify.request(client, :delete, "/api-keys/#{URI.encode(id)}", body)
end
@doc "Get the details of an API key (last activity, allowed IPs, …)."
@spec get(Coffrify.t(), String.t()) :: {:ok, map()} | {:error, Exception.t()}
def get(client, id), do: Coffrify.request(client, :get, "/api-keys/#{URI.encode(id)}")
@doc """
Rotate an API key. Returns a NEW key value; the old one stays valid for
`grace_days` (default 7, max 30).
"""
@spec rotate(Coffrify.t(), String.t(), keyword()) :: {:ok, map()} | {:error, Exception.t()}
def rotate(client, id, opts \\ []) do
body = %{grace_days: Keyword.get(opts, :grace_days, 7)}
Coffrify.request(client, :post, "/api-keys/#{URI.encode(id)}/rotate", body)
end
end