Phx.Gen.Auth Preload User Association

I’m using Phx.Gen.Auth for authentication, and the navigation menu has a list of the user’s projects. This navigation is on every page in the app, so I’m wondering if there is an easy way to preload the list of user’s projects into the @current_user used in Phx.Gen.Auth. Otherwise I am doing this via plug, but it seems like it would be more efficient to have the association preloaded to the @current_user and just go with that. Anyone have thoughts?

Hi,

I have a User and and associated Profile which holds relevant information about the User that I use for rendering etc. To do this just modify the fetch_current_user function in user_auth.ex file.

def fetch_current_user(conn, _opts) do
    {user_token, conn} = ensure_user_token(conn)
    user = user_token && Accounts.get_user_by_session_token(user_token)
    profile = user && Accounts.get_profile!(user.profile_id)
    conn
    |> assign(:current_user, user)
    |> assign(:profile, profile)
  end

Hope this helps.

Andrew

3 Likes