paulstatezny

paulstatezny

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.

Showing Posts 3 to 1

paulstatezny

paulstatezny OP

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.

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 #2
sfusato

sfusato

Open the registration endpoint only if a valid invitation token is provided.

Then an admin has a form with one input field (an email address) and a submit button (Invite).

Looking at the original design spec, you could set up the whole invitations_tokens like the users_tokens is set up. The base logic behind the two should be more or less the same.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews