Best way to generate an UUID for the id field?

Hello,

I am having a hard time to find the proper way to implement the UUID method on the field in my schema and my migrations.

So far I found one article on medium https://medium.com/@brucepomeroy/specifying-primary-key-values-with-ecto-57405b7ecbc5 and the doceumntation https://hexdocs.pm/ecto/Ecto.UUID.html.

The example that the medium article offers seems outdated and it looks like this:

@doc""" Generated migration for companies with the id field using UUID 4"""
defmodule MyApp.MyMigration do
  use Ecto.Migration
  def change do
    create table(:companies, primary_key: false) do
      add :id, :uuid, primary_key: true
      add :title, :string
      timestamps()
    end
  end
end

Then the schema looks like this

@doc """ Generated schema for company with autogenerated uuid"""
defmodule MyApp.Company do
  use Ecto.Schema
  @primary_key {:id, :binary_id, autogenerate: true}
  @derive {Phoenix.Param, key: :id}
  schema "companies" do
    field :title, :string
    timestamps()
  end
end

My question is does this work with absinthe and is UUID 4 secure enough?
Wouldn’t be better to use a more powerful uuid, composed from letters and numbers, is there a package that does this?

Thanks in advance

I don’t see any reason why it would not work with Absinthe. If You use node interface, You will see that GraphQL has a very simple way to generate unique node id.

Secure enough? I don’t think it is used for security reason, but to ensure uniqueness. Unless guessing the id leads to security issues.

I have also used KSUID with Ecto without problem. It does add time order to keys.

There is an example of KSUID in Mastering Elixir (Self-published / Packt)

1 Like

Unless guessing the id leads to security issues.

Well that was my way of thinking to not allow an outsider to guess the user id and add some changes.
For example: to subscribe them to a service or deleting their account.

I come from node ecosystem where javascript can easily become a very dangerous thing especially because there are so many ways to do things.
I would like to keep this topic open for other opinions and views as well.
Thanks for your point of view @ kokolegorille.

If You have an authorization system in place, then putting some random id should not affect the security of your system.

User identity can be managed by sessions, cookies, or tokens in case of API.

If You have an authorization system in place

You have a valid point there, that is why I am struggling to create one and make it open source to help others as well.

1 Like