A user is being logged in as another user sometimes in my LiveView application

There are 2 steps for authentication in my application.

  1. When a user logged in with OAuth2(OIDC)
defmodule MyApp.AuthController do

  def oauth2_callback(conn, %{"code" => code}) do
    with {:ok, %{id_token: id_token}} <- OAuth2.get_id_token(code),
         {:ok, %{key: provider_key}} <- OAuth2.verify_id_token(id_token),
         {:ok, user} <- Accounts.sign_in(%{provider_key: provider_key}) do
      |> put_session(:user_id, user.id)
      |> redirect(to: ~p"/")
  1. Authentication with LiveView Hook (No authentication with plug)
defmodule MyAppWeb.AuthHook do

  def on_mount(:default, _params, %{"user_id" => user_id}, socket) do
    socket =
      |> assign_new(:current_user, fn -> Accounts.get_user(user_id) end

    {:cont, socket}

in router

scope "/", MyAppWeb do
  live_session, :user, on_mount: [MyAppWeb.AuthHook] do

Does not performing authentication in a plug and directly using the user_id stored in the session in a LiveView hook have the potential to cause a situation where a user can be logged in as another user?

Given that %{"user_id" => user_id} in your on_mount is coming from the session and the session is signed and/or encrypted it should be a safe way to pick up your current user. Because of the signing/encryption (and keeping the secrets safe) it should not be possible to change that user_id by others even though it travels out of your server to user’s browsers and back. (SECRET_KEY_BASE is used for this signing/encryption of the session cookie. It can be found in config/runtime.exs)

Was it just questioning if it safe enough or are you actually experiencing different users being logged in?

on logout are you disconnecting the user?

1 Like