Ash FrameworkAF
Ash Framework3y ago
8 replies
Robert Graff

Identity on two attributes causing errors

I have an identity on two attributes (context, and token). I would expect this to require a unique context <> token. But it's not allowing duplicate contexts.

Here's my resource:

defmodule Iterup.Account.UserToken do
  use Ash.Resource,
    data_layer: AshPostgres.DataLayer

  @rand_size 32

  postgres do
    table("user_tokens")
    repo(Iterup.Repo)
  end

  attributes do
    uuid_primary_key(:id)

    attribute :sent_to, :ci_string, allow_nil?: false
    attribute :token, :binary, allow_nil?: false
    attribute :context, :string, allow_nil?: false
    attribute :confirmed_at, :utc_datetime

    create_timestamp :inserted_at
  end

  relationships do
    belongs_to :user, Iterup.Account.User
  end

  identities do
    identity :context_token, [:context, :token]
  end

  code_interface do
    define_for(Iterup.Account)
    define(:create_session_token, action: :session_token)
  end

  actions do
    create :session_token do
      accept [:sent_to]
      argument :user_id, :uuid, allow_nil?: false
      change manage_relationship(:user_id, :user, type: :append)
      change set_attribute(:token, :crypto.strong_rand_bytes(@rand_size))
      change set_attribute(:context, "session")
    end
  end
end


Here's the error:

# First call is successful
session_token_1 = UserToken.create_session_token!(%{user_id: user.id, sent_to: user.email})

...

# Second call is unsuccessful
session_token_2 = UserToken.create_session_token!(%{user_id: user.id, sent_to: user.email})
...
↳ anonymous fn/3 in Ash.Changeset.with_hooks/3, at: lib/ash/changeset/changeset.ex:1573
** (Ash.Error.Invalid) Input Invalid

* Invalid value provided for context: has already been taken.


What am I missing?
Was this page helpful?