
create type claims as (
  aud uuid,
  iat timestamptz,
  ip4 inet,
  dat jsonb
);

create or replace function get_claims_default_aud ( ) returns uuid as $$
  -- code to determine default audience (aud)
  -- this is likely your account.id

  select uuid_nil();
$$ language sql strict immutable;

create or replace function get_claims_default_iat ( ) returns timestamptz as $$
  -- code to determine default issued timestamp (iat)

  select current_timestamp;
$$ language sql strict immutable;

create or replace function get_claims_default_ip4 ( ) returns inet as $$
  -- code to determine default ip address (ip4)

  select inet_client_addr();
$$ language sql strict immutable;

create or replace function get_claims_default_dat ( ) returns json as $$
  -- code to determine default extra data (dat)

  select null::json;
$$ language sql strict immutable;

create or replace function get_claims_default ( ) returns claims as $$
  select (
    get_claims_default_aud(),
    get_claims_default_iat(),
    get_claims_default_ip4(),
    get_claims_default_dat()
  )::claims;
$$ language sql strict immutable;

create or replace function get_claims ( ) returns claims as $$
  select coalesce(
    nullif(current_setting('cran.claims', true), '')::claims,
    get_claims_default()
  );
$$ language sql strict immutable;

create or replace function set_claims (
  uuid = get_claims_default_aud(),
  jsonb = get_claims_default_dat()
) returns void as $$
  select set_config('cran.claims', (
    $1, get_claims_default_iat(), get_claims_default_ip4(), $2
  )::claims::text, true);
$$ language sql strict immutable;
