tenzil

tenzil

hi @danschultzer I am planning on adding a referral code in Login form, i generated the templates and added referral_code as text field, in the generated registration form. I have few doubts with the custom controllers
(The ask is): I want to add this referral code only on registration controller, in a transactional way. if code given , then i check presence of code and finally create user. If code not given, i directly create user.
I use pow_assent. I have read about invitation extension but i want to go with my own.

Doubts:

  1. I want to modify only create action of registration controller. Do i need to modify the routes as well?
  2. Do i need to add all action for both registration, session controllers and point their routes as mentioned in Custom controllers — Pow v1.0.11.
  3. Is there a way to overwrite only create action of registration controller?

Showing Posts 28 to 19

tenzil

tenzil OP

Hi @danschultzer, i gone through the code. Looks like unconfirmed_email carries nil value on user creation in my custom registration controller. So i added a check to update unconfirmed_email.
Now its working as expected. After registration, confirmation link is sent. post clicking the confirmation link, the account is confirmed.

def changeset(user_or_changeset, attrs) do
    user_or_changeset
    |> pow_changeset(attrs)
    |> pow_extension_changeset(attrs)
    |> Ecto.Changeset.validate_required([:fname, :lname, :dob, :gender])
    |> set_age()
    |> unconfirm_email
  end

  defp unconfirm_email(%Ecto.Changeset{valid?: true, changes: %{email: email}} = changeset) do
    put_change(changeset, :unconfirmed_email, email)
  end 
    

danschultzer

danschultzer

Pow Core Team

You would need to add a custom controller action for that. The logic is super simple though: pow/lib/extensions/email_confirmation/phoenix/controllers/confirmation_controller.ex at v1.0.19 · pow-auth/pow · GitHub

You just have to load the user by the token with PowEmailConfirmation.Plug.load_user_by_token/2 and then call PowEmailConfirmation.Plug.Plug.confirm_email/2 to confirm it.

tenzil

tenzil OP

Thank you @danschultzer for the quick response.

Yes, i recently updated it, like 2 days ago.

I updated few lines to get it work for me.

@spec send_confirmation_email(map(), Conn.t()) :: any()
  def send_confirmation_email(user, conn) do
    url               = confirmation_url(conn, user)
    unconfirmed_user  = %{user | email: user.unconfirmed_email || user.email}
    email             = Mailer.email_confirmation(conn, unconfirmed_user, url)

    Pow.Phoenix.Mailer.deliver(conn, email)
  end

  defp confirmation_url(conn, user) do
    token = PowEmailConfirmation.Plug.sign_confirmation_token(conn, user)
    ConfirmationController.routes(conn).url_for(conn, ConfirmationController, :show, [token])
  end

Now i got “The email address has been confirmed” and got redirected to registration edit page.
How to register/signup an unconfirmed email, and redirect to a different/custom url post confirmation.

danschultzer

danschultzer

Pow Core Team

It has changed since then: pow/lib/extensions/email_confirmation/phoenix/controllers/controller_callbacks.ex at v1.0.19 · pow-auth/pow · GitHub

If you use 1.0.19 and up, then all tokens need to be signed before they can be used.

tenzil

tenzil OP

Hi @danschultzer, hope you are doing well. My custom registration controller is working fine, with and without referral codes. Now the thing is, i added few extensions “reset password and confirmation with emails”. The setup is working fine for reset password. but it didn’t for confirmation. I googled and found out this link pow/lib/extensions/email_confirmation/phoenix/controllers/controller_callbacks.ex at 6518aaad2f1cbb680ac8ff8e8760021f00011717 · pow-auth/pow · GitHub
and added this function. It worked fine. I send the email as well.

But the issue is, when i click the link. its not confirming the account, its throwing “Email couldn’t be confirmed”

The expectation is, I need to register a unconfirmed account and send a confirmation email using which user can access the website.

tenzil

tenzil OP

Sync user function worked!

defmodule MyAppWeb.Pow.User do
  @spec sync_user(Plug.Conn.t(), map()) :: Plug.Conn.t()
  def sync_user(conn, user) do
    config = Pow.Plug.fetch_config(conn)
    plug   = Pow.Plug.get_plug(config)

    plug.do_create(conn, user, config)
  end
end
tenzil

tenzil OP

@danschultzer, as i was creating user with pow_create(params), I am not able to signin the user after registration. How to signup the user after this? I am going to try with sync user function.

danschultzer

danschultzer

Pow Core Team

You can both customize messages and redirect paths. The conn is passed along so you could even add some conditional based on, e.g. the @changeset assign for the message or route.

But the way @tenzil resolved it is what I prefer since it’s much more explicit, and it makes sense when you e.g. add controller test to it. One idea I have of Pow is that in most cases it should work more as a helper than a framework, so whenever you customize stuff you basically write it all out so it’s easy to test, understand and take control of rather than depending on the library.

I definitely want to ease these steps so please do let me know what could be improved!

tenzil

tenzil OP

Yes you can make any controller to overwrite a specific route and its action.

I have overwritten Pow registration controller with just a regular controller. For my understanding , i kind of added made it look alike. When you ran mix pow.phx.gen.templates, it creates a pow/registration/files inside lib/templates. I did the same added pow/registration_controller inside lib/controllers.

Entire Code Block

I created a module and named it pow/.
scope "/" do
    pipe_through [:browser]
    resources "/registration", MyAppWeb.Pow.RegistrationController, singleton: true, only: [:create]
  end
controller:
defmodule MyAppWeb.Pow.RegistrationController do
  use MyAppWeb, :controller

  # def new(conn, _params) do
  #   # We'll leverage [`Pow.Plug`](Pow.Plug.html), but you can also follow the classic Phoenix way:
  #   # changeset = MyApp.Users.User.changeset(%MyApp.Users.User{}, %{})

  #   changeset = Pow.Plug.change_user(conn)

  #   render(conn, "new.html", changeset: changeset)
  # end

  def create(conn, %{"user" => user_params}) do
    # We'll leverage [`Pow.Plug`](Pow.Plug.html), but you can also follow the classic Phoenix way:
    # user =
    #   %MyApp.Users.User{}
    #   |> MyApp.Users.User.changeset(user_params)
    #   |> MyApp.Repo.insert()

    case MyApp.Users.create_user_using_referral(user_params) do
      {:ok, user} ->
        conn
        |> put_flash(:info, "Welcome, Lets find your spouse!")
        |> redirect(to: Routes.dashboard_path(conn, :index))
      {:invalid_code, changeset} ->
        conn
        |> put_flash(:error, "You have entered an invalid code")
        |> render("new.html", changeset: changeset, action: Routes.registration_path(conn, :create))
      {:error, changeset} ->
        conn
        |> put_flash(:error, "Please correct the errors")
        |> render("new.html", changeset: changeset, action: Routes.registration_path(conn, :create))
    end
  end
end

And i used pow custom context as well.

defmodule MyApp.Users do
   use Pow.Ecto.Context,
        repo: MyApp.Repo,
       user: MyApp.Users.User

  def create_user_using_referral(params) do
    case params["referral_code"] do
      nil -> pow_create(params)
      "" -> pow_create(params)
      code ->
        case MyApp.Trial.get_by_referral_code(code) do
          nil ->
            changeset = User.changeset(%User{}, params)
            Ecto.Changeset.add_error(changeset, :referral_code, "Entered code is invalid", validation: :invalid)
            {:invalid_code, changeset}
          referral_code ->
            pow_create(params)
        end
    end
  end
end
AlchemistCamp

AlchemistCamp

What was invovled in setting up a custom controller? Was simply naming a controller MyAppWeb.UserController and overwriting the functions in Pow?

I’m interested in doing this. The primary pain I hit comes from having controller actions hidden in a library and not having control over how possible issues are handled, redirects, error messages, etc.

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
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
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews