Daniel Zendejas
Daniel Zendejas

Reputation: 486

How to expire a value in an Ecto Schema?

Let's say there is a schema:

schema "players" do
  :key, :string
  :reset_key_token, :string
end

A hash is set in the :reset_key_token field when the user wants to reset their key. The idea is that the :reset_key_token should be put back to nil say, after a week the token was set. My question is:

Is there a standard way to expire the value of an Ecto Schema?

I have been looking for some time now, but haven't found anything on the subject yet. However, I found this MySQL question and thought of following the same idea:

1.- Add a :reset_key_token_expires, Ecto.DateTime to the schema.

2.- Before a read (in my case I need it also before a write), check :reset_key_token_expires and set it to nil if the time has passed.

But I would like to see if anyone that has done this before could provide some answers first.

Thanks for the help!

Upvotes: 0

Views: 235

Answers (1)

Dogbert
Dogbert

Reputation: 222388

Do you really need to set the value to nil after it expires? For this use case, where you just want to prevent the token from being used after expiration, I'd just compare the value with the current time in the controller which handles resetting the key. Here's some code:

def reset_key(conn, %{"username" => username, "reset_key_token" => reset_key_token}) do
  user = Repo.get_by!(User, username: username)
  if reset_key_token == user.reset_key_token do
    case DateTime.compare(user.reset_key_token_expires, DateTime.utc_now) do
      :gt ->
        # token is still valid
      _ ->
        # token is expired
    end
  else
    # token is invalid
  end
end

Upvotes: 1

Related Questions