Thanks, Chris. Changing that has me a bit further. I am sure you knew I would run into problems once I started redirecting. I hope you might be able to help a little bit more.
As I mentioned above I am trying to add a subdomain after a user logs in (As they may be able to access multiple subdomains). By default I am directing them to the first subdomain.
I have a Plug.check_session to see if there is a user_id in the session cookie. If there is an there is no subdomain on the host I add in default subdomain and redirect to the new url.
If there is a subdomain I pass it through adding the user as the current_user.
defmodule BookingCentralWeb.Plugs.CheckSession do
import Plug.Conn
alias BookingCentral.Accounts
def init(opts), do: opts
def call(conn, _opts) do
user_id = get_session(conn, :user_id)
case user_id && Accounts.get_user_by_id(user_id) do
nil ->
assign(conn, :current_user, nil)
user ->
orgs = Enum.map(user.organisations, fn (x) -> x.subdomain end)
case get_subdomain(conn.host) do
"" ->
subdomain = get_first_subdomain(orgs)
url = %URI{host: subdomain <> "." <> conn.host, port: 4000}
conn = Phoenix.Controller.put_router_url(conn, url)
conn = assign(conn, :current_user, user)
Phoenix.Controller.redirect(conn, external: BookingCentralWeb.Router.Helpers.dashboard_url(conn, :index))
_ ->
assign(conn, :current_user, user)
end
end
end
defp get_subdomain(host) do
root_host = BookingCentralWeb.Endpoint.config(:url)[:host]
String.replace(host, ~r/.?#{root_host}/, "")
end
defp get_first_subdomain([head | _tail]) do
head
end
I changed my index action on the Dashboard Controller on the basis that the host will include the subdomain by this stage:
def index(conn, _params) do
render(conn, "index.html")
end
Running this when I authenticate it adds the subdomain and redirects but then I end up at the login page, presumably because I get a new session for eth subdomain. I modified the config in my endpoint.ex:
plug Plug.Session,
store: :cookie,
key: "_booking_central_key",
signing_salt: "H4nzWhe9",
allow_hosts: [".localhost"],
domain: ".localhost"
But now I get a CSRF error:
invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header
Any direction or examples will be greatly appreciated.