Hello all,
Q1) how can I assign subdomain to a user from elixir code ( say when he want to create a different instance of an app)?
Q2) How can I query whether a particular subdomain exists or not?
I found “dig” could be a possible solution, just wanna be sure.
thanks.
how can I assign subdomain to a user from elixir code ( say when he want to create a different instance of an app)?
Save their subdomain into your database and reference it to the user.
How can I query whether a particular subdomain exists or not?
Ask the database.
The plugs for this could look like (adapted from Subdomains With Phoenix - Gazler)
defmodule MyApp.Plugs.SubdomainExtractor do
@moduledoc "Extracts subdomains and puts them into `conn.private`"
@behaviour Plug
import Plug.Conn, only: [put_private: 3]
def init(_opts) do
MyApp.Endpoint.config(:url)[:host]
end
def call(%Plug.Conn{host: host} = conn, root_host) do
case extract_subdomain(host, root_host) do
subdomain when byte_size(subdomain) > 0 ->
put_private(conn, :subdomain, subdomain)
_ ->
conn
end
end
defp extract_subdomain(host, root_host) do
String.replace(host, ~r/.?#{root_host}/, "") # not the most efficient way
end
end
and then some plug down the line looks up the subdomain in conn.private[:subdomain]
in your database and assigns it to a user.
defmodule MyApp.Plugs.SubdomainMatcher do
@moduledoc "Matches a subdomain in `conn.private` to a user"
@behaviour Plug
import Plug.Conn, only: [assign: 3]
def init(opts), do: opts
def call(%Plug.Conn{private: %{subdomain: subdomain}}}, _opts) do
case MyDB.Accounts.lookup_for_subdomain(subdomain) do
%Account{user_id: user_id, id: account_id} ->
conn
|> assign(:user_id, user_id)
|> assign(:account_id, account_id)
_not_found ->
conn # or return 403
end
end
def call(conn, _opts) do
conn
end
end
That is, if you need this functionality.
Q1) how can I assign subdomain to a user from elixir code ( say when he want
to create a different instance of an app)?
An actual “subdomain” with a resolvable address? You need to create a
DNS entry for that.
Q2) How can I query whether a particular subdomain exists or not?
:inet.gethostbyname('something.example.com', :inet)
would work,
though if you have access to the DNS provider for the main domain you
should be able to see the existing entries directly.
I would probably cache them locally for convenience and speed but that
could require handling synchronization if other processes have write
access.
An actual “subdomain” with a resolvable address? You need to create a
DNS entry for that.
If all subdomains point to the same server, a wildcard DNS record should probably be enough.
Thanks for the description sir, I’ll try this and let u if I will be able to make it work or if got any more doubt.
Thanks again☺️