~mlb/linkhut

5c770f5a23dee9327c3d51955facd3175195b5e0 — Matías Larre Borges 5 months ago 8dc2926
Fix e-mail verification flow
M lib/linkhut/accounts.ex => lib/linkhut/accounts.ex +5 -5
@@ 310,17 310,17 @@ defmodule Linkhut.Accounts do
    end
  end

  def confirm_email(token) do
  def confirm_email(user, token) do
    case EmailToken.verify(token, "confirm") do
      {:ok, token} -> validate_email_confirmation(token)
      {:ok, token} -> validate_email_confirmation(user, token)
      _ -> :error
    end
  end

  defp validate_email_confirmation(token) do
  defp validate_email_confirmation(user, token) do
    case get_by_confirmation_token(token) do
      %User{credential: _credential} = user ->
        mark_as_verified(user)
      %User{id: id, credential: _credential} = unverified_user when id == user.id ->
        mark_as_verified(unverified_user)

      _ ->
        :error

M lib/linkhut_web/controllers/settings/email_confirmation_controller.ex => lib/linkhut_web/controllers/settings/email_confirmation_controller.ex +15 -13
@@ 22,24 22,26 @@ defmodule LinkhutWeb.Settings.EmailConfirmationController do
  end

  def confirm(conn, %{"token" => token}) do
    with {:ok, token} <- Base.url_decode64(token),
         {:ok, value} <- Accounts.confirm_email(token) do
      case value do
        # If the email was already confirmed, we redirect without
        # a warning message.
        :already_confirmed ->
          redirect(conn, to: "/")
    if user = conn.assigns[:current_user] do
      with {:ok, token} <- Base.url_decode64(token),
           {:ok, value} <- Accounts.confirm_email(user, token) do
        case value do
          # If the email was already confirmed, we redirect without
          # a warning message.
          :already_confirmed ->
            redirect(conn, to: "/")

          _ ->
            conn
            |> put_flash(:info, "Email confirmed successfully.")
            |> redirect(to: "/")
        end
      else
        _ ->
          conn
          |> put_flash(:info, "Email confirmed successfully.")
          |> put_flash(:error, "Email confirmation link is invalid or it has expired.")
          |> redirect(to: "/")
      end
    else
      _ ->
        conn
        |> put_flash(:error, "Email confirmation link is invalid or it has expired.")
        |> redirect(to: "/")
    end
  end
end

M lib/linkhut_web/router.ex => lib/linkhut_web/router.ex +1 -1
@@ 160,7 160,7 @@ defmodule LinkhutWeb.Router do
  end

  scope "/_/", LinkhutWeb.Settings do
    pipe_through [:browser]
    pipe_through [:browser, :ensure_auth]

    get "/confirm", EmailConfirmationController, :confirm
  end