dewetblomerus

dewetblomerus

This is not important, I’m just curious about how it would be done.

The updated_at field on my User gets bumped on every login, even if no fields changed. Auth0 already saves all the history about successful and unsuccessful logins, so I only want updated_at to be bumped when one of the fields for the User resource is being changed to a different value.

I followed this guide and then made some changes and eded up with the following action:

    create :register_with_auth0 do
      argument :user_info, :map, allow_nil?: false
      argument :oauth_tokens, :map, allow_nil?: false
      upsert? true
      upsert_identity :unique_auth0_id

      # Required if you have token generation enabled.
      change AshAuthentication.GenerateTokenChange

      # Required if you have the `identity_resource` configuration enabled.
      change AshAuthentication.Strategy.OAuth2.IdentityChange

      change fn changeset, _ ->
        user_info = Ash.Changeset.get_argument(changeset, :user_info)

        changes = %{
          "email" => Map.get(user_info, "email"),
          "auth0_id" => Map.get(user_info, "sub")
        }

        Ash.Changeset.change_attributes(
          changeset,
          changes
        )
      end
    end

Showing Posts 1 to 10

jimsynz

jimsynz

Ash Core Team

If I’m reading the docs correctly when upsert_fields is empty then all fields except those with defaults are set on conflict. This would lead me to believe that you shouldn’t be seeing the updated_at changing if there are no other changes. Is that not the case?

dewetblomerus

dewetblomerus OP

I just confirmed, updated_at is definitely getting updated to now() on every login.

I do not see upsert_fields in my code or in the Ash.Changeset so I can not make sure if it is empty or not.

There are for-sure no other fields changing, just the updated_at.

Here is the changeset I am returning from the register_with_auth0 change:

Ash.Changeset<
  action_type: :create,
  action: :register_with_auth0,
  attributes: %{
    name: "De Wet Blomerus",
    auth0_id: "redacted",
    email: #Ash.CiString<"dewetblomerus@gmail.com">,
    email_verified: true,
    picture: "shortened"
  }
jimsynz

jimsynz

Ash Core Team

Thanks for the confirmation. I believe this could be solved by #760. Keep an eye on that issue for updates.

zachdaniel

zachdaniel

Creator of Ash

Yes, so since it’s a create or update, each login becomes an update. You can use the new {:replace_all_except, [:updated_at]} option to prevent that behavior.

dewetblomerus

dewetblomerus OP

Thanks a lot for remembering and circling back.

I might have found an error scenario that needs some work.

I updated to the following:

ash                         2.17.0   2.17.0   Up-to-date
ash_admin                   0.9.5    0.9.5    Up-to-date
ash_authentication          3.11.16  3.11.16  Up-to-date
ash_authentication_phoenix  1.9.0    1.9.0    Up-to-date
ash_phoenix                 1.2.23   1.2.23   Up-to-date
ash_postgres                1.3.60   1.3.60   Up-to-date

Then I tried this: upsert_fields { :replace_all_except, [:updated_at] }

I also tried this:

      upsert_fields {
        :replace_all_except,
        [:updated_at, :auth0_id, :id, :created_at]
      }

I also tried upsert_fields :replace_all

And since I was on a roll, I tried the following:

      upsert_fields {
        :replace,
        [:name, :email, :picture, :email_verified]
      }

All of the above yielded the same result. I get an error at login, but there is no error in the logs, just a rollback. Here are the logs:

[debug] Processing with RedWeb.AuthController
  Parameters: %{"code" => "the-code", "state" => "the-state"}
  Pipelines: [:browser]
[debug] QUERY OK db=4.3ms idle=1857.9ms
begin []
↳ anonymous fn/3 in Ash.Changeset.with_hooks/3, at: lib/ash/changeset/changeset.ex:1801
[debug] QUERY OK db=2.4ms
rollback []
↳ anonymous fn/3 in Ash.Changeset.with_hooks/3, at: lib/ash/changeset/changeset.ex:1801
[info] Sent 401 in 945ms

Link to my entire user

zachdaniel

zachdaniel

Creator of Ash

Can you try submitting the action in iex with that upsert_fields set? I’m not sure what the issue is currently.

dewetblomerus

dewetblomerus OP

While trying to get the output for this, I got stuck with something I have gotten stuck with a few times while using Ash. I am calling an Ash function with the wrong arguments, and the error message is trying to tell me something, but I am unable to translate the error message into how to fix it.

Here is what I tried:

auth0_id = "redacted"
email = "dewetblomerus@gmail.com"
user = Red.Accounts.User.get_by!(%{email: email})

user_info = %{
  "name" => "De Wet",
  "email" => email,
  "sub" => auth0_id
}

user
|> Ash.Changeset.for_update(
    :register_with_auth0,
    %{
      user_info: user_info,
      oauth_tokens: %{}
    }
  )
|> Red.Accounts.create!()

When I run this, I get the following error:

** (Ash.Error.Invalid) Input Invalid

* attribute email is required
    (ash 2.17.0) lib/ash/api/api.ex:2324: Ash.Api.unwrap_or_raise!/3
    /Users/dewet/code/ash/red/README.livemd#cell:7cjnls2owec2pmsah6gswm3qjxo6sxou:20: (file)

I tried to put email: email as part of the params map or the opts list arguments to Ash.Changeset.for_update but nothing I tried changed the error.

changeset.errors is as follows:

[
  %Ash.Error.Changes.Required{
    field: :email,
    type: :attribute,
    resource: Red.Accounts.User,
    changeset: nil,
    query: nil,
    error_context: [],
    vars: [],
    path: [],
    stacktrace: #Stacktrace<>,
    class: :invalid
  }
]
zachdaniel

zachdaniel

Creator of Ash

This seems strange. Is this your own action? Do you have a change or something in the action attempting to set the email based on some input, but setting it to nil?

dewetblomerus

dewetblomerus OP

This is my current action:

    create :register_with_auth0 do
      argument :user_info, :map, allow_nil?: false
      argument :oauth_tokens, :map, allow_nil?: false
      upsert? true
      upsert_identity :unique_auth0_id

      change fn changeset, _ ->
        user_info = Ash.Changeset.get_argument(changeset, :user_info)

        changes =
          user_info
          |> Map.take([
            "email_verified",
            "email",
            "name",
            "picture"
          ])
          |> Map.put("auth0_id", Map.get(user_info, "sub"))

        Ash.Changeset.change_attributes(
          changeset,
          changes
        )
      end
    end

It is still very close to what I had after following this guide: https://ash-hq.org/docs/guides/ash_authentication/latest/tutorials/auth0-quickstart

dewetblomerus

dewetblomerus OP

I am seeing something else in the changeset that might help:

#Ash.Changeset<
  action_type: :update,
  action: :register_with_auth0,
  attributes: %{name: "De Wet"},
  relationships: %{},
  arguments: %{
    user_info: %{
      "email" => "dewetblomerus@gmail.com",
      "name" => "De Wet",
      "sub" => "google-oauth2|redacted"
    },

Under attributes, it only has a name, but I passed in a name and email.

This code works 100% for signup and login.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

xinz
Hello everyone! :waving_hand: I’d like to share JSONSchex, a JSON Schema Draft 2020-12 library for Elixir focused on correctness, repeat...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews