paulstatezny

paulstatezny

Phx_gen_auth with invite-only applications

Regarding the phx.gen.auth generator: https://github.com/aaronrenner/phx_gen_auth

I’m wondering, does anyone have recommendations for modifying the generated code for an application that doesn’t have public registration? That is, an application where you set up “administrators” to start off, and then from that point on the way that users join is by invitation. This would be typical of an application used by a business, with only its employees as users.

Most Liked

joaquinalcerro

joaquinalcerro

So I just recently modified my code to adhere to the invitation use case because as you mention, it is a pretty common business use case.

I am sure there are many ways to do it but this is my approach. It is important to mention that I didn’t wanted to change the library’s flow that much so in the sake of clarity, some copy and paste was done with the required adjustments for the use case. One last important comment: this code is still not in production environment but working in development as expected.

I will also like to have anyones comments and feedback to make this code better and safer before it goes into production.

1. Add the required routes to handle the invitation

This routes require that the user be authenticated

get "/users/invite", UserInvitationController, :new
post "/users/invite", UserInvitationController, :create

This routes do no require the user to be authenticated

get "/users/invite/:token", UserInvitationController, :accept
put "/users/invite/:token/:id/invite_update", UserInvitationController, :update_user

2. Add a user invitation controller

The Flow:
a. Authorized user creates the invitation (new) and a user_invitation is sent by email
b. The invited user clicks the link (accept) and updates its name or other required fields.
c. The user is updated in the database (update_user)
d. Normal confirmation flow (in my case, we use this confirmation flow for legal purposes you might not need it. If this is the case, you might want to update the confirmation user’s field in step 3.

defmodule EprWeb.UserInvitationController do
  use EprWeb, :controller

  alias Epr.Accounts
  alias Epr.Accounts.User

  def new(conn, _params) do
    changeset = Accounts.change_user_invitation(%User{})
    render(conn, "new.html", changeset: changeset)
  end

  def create(conn, %{"user" => user_params}) do
    case Accounts.invite_user(user_params) do
      {:ok, user} ->
        {:ok, _} =
          Accounts.deliver_user_invitation_instructions(
            user,
            &Routes.user_invitation_url(conn, :accept, &1)
          )

        conn
        |> put_flash(:info, "User invited successfully.")
        |> redirect(to: "/users")

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end

  def accept(conn, %{"token" => token}) do
    case Accounts.fetch_user_from_invitation(token) do
      {:ok, user} ->
        changeset = Accounts.change_user_invitation(user)
        render(conn, "accept.html", changeset: changeset, user: user, token: token)

      :error ->
        invalid_token(conn)
    end
  end

  def update_user(conn, %{"user" => user_params, "token" => token}) do
    case Accounts.accept_invitation(token, user_params) do
      {:ok, user} ->
        {:ok, _} =
          Accounts.deliver_user_confirmation_instructions(
            user,
            &Routes.user_confirmation_url(conn, :confirm, &1)
          )

        conn
        |> put_flash(:info, "User registered successfully.")
        |> redirect(to: "/")

      {:error, %Ecto.Changeset{} = changeset} ->
        case Accounts.fetch_user_from_invitation(token) do
          {:ok, user} ->
            render(conn, "accept.html", changeset: changeset, user: user, token: token)

          :error ->
            invalid_token(conn)
        end

      :error ->
        invalid_token(conn)
    end
  end

  defp invalid_token(conn) do
    conn
    |> put_flash(:error, "Invitation link is invalid or it has expired.")
    |> redirect(to: "/")
  end
end

3. Templates and views are very simple and straight forward

4. In your context… in my case, Accounts Context

  def change_user_invitation(%User{} = user, attrs \\ %{}) do
    User.invitation_changeset(user, attrs)
  end

  def deliver_user_invitation_instructions(%User{} = user, invitation_url_fun)
      when is_function(invitation_url_fun, 1) do
    if user.confirmed_at do
      {:error, :already_confirmed}
    else
      {encoded_token, user_token} = UserToken.build_email_token(user, "invitation")
      Repo.insert!(user_token)
      UserNotifier.deliver_invitation_instructions(user, invitation_url_fun.(encoded_token))
    end
  end

  def fetch_user_from_invitation(token) do
    with {:ok, query} <- UserToken.verify_email_token_query(token, "invitation"),
         %User{} = user <- Repo.one(query) do
      {:ok, user}
    else
      _ -> :error
    end
  end

  def accept_invitation(token, user_params) do
    with {:ok, query} <- UserToken.verify_email_token_query(token, "invitation"),
         %User{} = user <- Repo.one(query),
         {:ok, changeset} <- valid_invitation_changeset(user, user_params),
         {:ok, %{user: user}} <- Repo.transaction(accept_invitation_multi(user, changeset)) do
      {:ok, user}
    else
      {:error, %Ecto.Changeset{} = ch} -> {:error, ch}
      _ -> :error
    end
  end

  defp valid_invitation_changeset(user, params) do
    changeset = User.accept_invitation_changeset(user, params)

    case changeset.valid? do
      true -> {:ok, changeset}
      false -> {:error, changeset}
    end
  end

  defp accept_invitation_multi(user, user_update_changeset) do
    Ecto.Multi.new()
    |> Ecto.Multi.update(:user, user_update_changeset)
    |> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["invitation"]))
  end

5. In your user_token.ex

I am keeping the invitation validity for 7 days

@invite_validity_in_days 7

Added the “invitation” case in the days_for_context validation time

defp days_for_context("invitation"), do: @invite_validity_in_days

6. Finally, modify your user_notification.ex file to your specific case

I just added a function to handle the invitation case

  def deliver_invitation_instructions(user, url) do
  ....
  end

I think this is it…

Hope this helps,

Best regards,

12
Post #3
paulstatezny

paulstatezny

joaquinalcerro Thanks for all that detail! The path I decided to start with was similar, but I actually converted the confirmation workflow to an invitation workflow. I don’t know if it’s a bad idea, but I figure accepting the invitation is implicitly confirming your email.

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44139 214
New

We're in Beta

About us Mission Statement