My goal as expressed in the code examples below is the following:
When a user logs in and is NOT a subscriber they should be forwarded to the subscriber page.
If they ARE a subscriber then they should be forwarded to their user page - IE users/#{id}
.
I have working code that redirects to a page that is NOT a user page and it works fine. This is expressed in the first example below. The second code example is a modified version of the first that has been changed in an attempt to get the result expressed in this posting and does not work.
Working code without user redirect
defmodule AppxWeb.LoginController do
use AppxWeb, :controller
alias Appx.Accounts.User
alias Appx.Repo
def index(conn, _params) do
render(conn, "index.html")
end
def create(conn, %{"email" => email_address}) do
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(subscriber?))
nil ->
conn
|> put_flash(:error, "#{email_address} not found")
|> redirect(to: redirect_path(:index))
end
end
defp redirect_path(true) do
"/dashboard"
end
defp redirect_path(false) do
"/subscribe"
end
end
Non working code
The code below gives the following error when the user attempts to log in as a non subscriber
defmodule AppxWeb.LoginController do
use AppxWeb, :controller
alias Appx.Accounts.User
alias Appx.Repo
def index(conn, _params) do
render(conn, "index.html")
end
def create(conn, %{"email" => email_address}) do
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(subscriber?, user_id)) # added second argument
nil ->
conn
|> put_flash(:error, "#{email_address} not found")
|> redirect(to: redirect_path(:index))
end
end
defp redirect_path(true, id) do # added second parameter
"/user/#{id}" # added id
end
defp redirect_path(false) do
"/subscribe"
end
end
I also tried
defp redirect_path(false, _id) do # added id ?
"/subscribe"
end