If user is logged in redirect to X page

What would be the best approach to have an auto-redirect for a user that is logged in already, so X user logs in, then close the site but then comes back it, he should be redirected to the admin/dashboard. I’m using Coherence and Coherence Assent. I’m thinking this should be done in the router but not sure how

Here is my current router
defmodule MagnifyWeb.Router do
use MagnifyWeb, :router
use Coherence.Router
use CoherenceAssent.Router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug Coherence.Authentication.Session
  end

  pipeline :protected do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug Coherence.Authentication.Session, protected: true
  end

  pipeline :admin_layout do
    plug :put_layout, {MagnifyWeb.LayoutView, :admin}
  end

  scope "/" do
    pipe_through :browser
    coherence_routes()
    coherence_assent_routes()
  end

  scope "/" do
    pipe_through :protected
    coherence_routes :protected
  end

  scope "/", MagnifyWeb do
    pipe_through :browser # Use the default browser stack
    get "/", HomeController, :index
    get "/about", AboutController, :index
  end

  scope "/", MagnifyWeb do
    pipe_through [:protected, :admin_layout]
    # add protected resources below
    resources "/dashboard", DashboardController
    resources "/magnets", MagnetController
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

end

You can add a plug to your :browser pipeline that would redirect logged in users (users that have user_id in their conn.assigns or whatever coherence uses) to X page.

defmodule MagnifyWeb.Plugs.Redirector do
  @moduledoc "Redirects logged in users to X page."

  alias MagnifyWeb.Router.Helpers, as: Routes
  import Phoenix.Controller, only: [redirect: 2]

  def init(opts) do
    opts
  end

  def call(%Plug.Conn{assigns: assigns} = conn, _opts) do
    case assigns do
      %{user_id: user_id} when not in_nil(user_id) ->
         redirect(conn, to: Routes.your_page_path(conn, :action))
      _other ->
         conn # do nothing
    end
  end
end
1 Like

How would you want to differ between the user that reopens his browser from a user that tries to surf your site?

It sounds to me, as if with your construct users won’t be able anymore do to anything but look at the dashboard.

Also it reads as if you forbid deeplinking by this.

Overall, it reads like a bad idea.

If though, you mean that you want to redirect to dashboard directly after they log in, a simple redirect conn, to: "/dashboard" in the seesion create action should be sufficient.

1 Like