Storing last seen timestamp - is this code correct?

I was looking at storing a ‘last seen’ timestamp in my phoenix project and came across this blog post: How to store ‘last seen’ for users in Phoenix | Plausible Analytics, however it doesn’t appear correct and I wanted to sanity check my understanding.

Here’s the key bit of code:

def call(conn, _opts) do
    last_seen = get_session(conn, :last_seen)
    user = conn.assigns[:current_user]

    cond do
      user && last_seen && last_seen < (unix_now() - @one_hour) ->
        persist_last_seen(user) # Saves last_seen to DB
        put_session(conn, :last_seen, unix_now())
      user && !last_seen ->
        put_session(conn, :last_seen, unix_now())
      true ->
        conn
    end
  end

A few questions:

  1. This doesn’t look like it will update last_seen for the first hour in a new session?
  2. Why do we need to store last_seen in the session at all?

It feels like I can replace the above with much simpler code:

  def call(conn, _opts) do
    user = conn.assigns[:current_user]

    if user && DateTime.diff(unix_now(), user.last_seen) > @one_hour do
      persist_last_seen(user, unix_now())
    end

    conn
  end

NB. Both plugs assume the user was fetched in a previous plug.

Is my understanding correct on this? Thanks for the help.

1 Like