Changing page redirect on login based on database boolean

Problem
I want a user to login to my app and depending if the user is a “subscriber” (The column in the database titled subscriber is TRUE or FALSE) the page redirect after log in will point to a different page. It’s a simple conditional but I am unclear how to write the syntax for this. Here is the code so far. Scrolling further down I wrote pseudo code for what I want.

def create(conn, %{"email" => email_address}) do
    IO.inspect("created fake session")

    case Repo.get_by(User, email: email_address) do
      %User{id: user_id} ->


        conn
        |> put_session(:user_id, user_id)
        |> redirect(to: "/")

      nil ->
        conn
        |> put_flash(:error, "#{email_address} not found")
        |> redirect(to: session_path(conn, :index))
    end
  end

Pseudo code

 def create(conn, %{"email" => email_address}) do
    IO.inspect("created fake session")

    case Repo.get_by(User, email: email_address) do
      %User{id: user_id} ->

    #___________________BEGIN Pseudo code
        conn
        |> put_session(:user_id, user_id)

        if(User.subscribed) do
          redirect(to: "/content")
        else
           redirect(to: "/signup")
        end
    #___________________END Pseudo code

      nil ->
        conn
        |> put_flash(:error, "#{email_address} not found")
        |> redirect(to: session_path(conn, :index))
    end
  end
  def create(conn, %{"email" => email_address}) do
    IO.inspect("created fake session")

    case Repo.get_by(User, email: email_address) do
      %User{id: user_id, subscriber: subscriber?} ->
        conn
        |> put_session(:user_id, user_id)
        |> redirect(to: redirect_path(conn, subscriber?))

      nil ->
        conn
        |> put_flash(:error, "#{email_address} not found")
        |> redirect(to: session_path(conn, :index))
    end
  end

  @spec redirect_path(Plug.Conn.t(), subscriber? :: boolean) :: path :: String.t()
  defp redirect_path(conn, true) do
    content_path(conn, :index) # or whatever route/action corresponds to "/content"
  end
  defp redirect_path(conn, false) do
    signup_path(conn, :index) # or whatever route/action corresponds to "/signup"
  end
1 Like

Thanks, can you tell me what the purpose of this line is:

@spec redirect_path(Plug.Conn.t(), subscribed? :: boolean) :: path :: String.t()

It’s a function spec for you or anyone else to better understand what this function accepts and what it returns without reading the function body. It can also be checked by tools like dialyzer.