61 lines
1.6 KiB
Elixir
61 lines
1.6 KiB
Elixir
defmodule MetaWeb.UserRegistrationController do
|
|
use MetaWeb, :controller
|
|
|
|
alias Meta.Captcha
|
|
alias Meta.Accounts
|
|
alias Meta.Accounts.User
|
|
alias MetaWeb.UserAuth
|
|
|
|
defp is_registration_enabled?() do
|
|
Application.get_env(:meta, :enable_registration)
|
|
end
|
|
|
|
def new(conn, _params) do
|
|
changeset = Accounts.change_user_registration(%User{})
|
|
{captcha_text, captcha_result} = Captcha.generate()
|
|
|
|
with_notice = unless is_registration_enabled?() do
|
|
conn
|
|
|> put_flash(:error, "Registration is disabled for the time being.")
|
|
else
|
|
conn
|
|
end
|
|
|
|
with_notice
|
|
|> assign(:captcha, captcha_text)
|
|
|> put_session(:captcha, captcha_result)
|
|
|> render("new.html", changeset: changeset)
|
|
end
|
|
|
|
def create(conn, %{"user" => user_params}) do
|
|
unless is_registration_enabled?() do
|
|
conn
|
|
|> redirect(to: Routes.user_registration_path(conn, :new))
|
|
else
|
|
attrs = user_params
|
|
|> Map.put("expected_captcha", get_session(conn, :captcha))
|
|
|
|
case Accounts.register_user(attrs) do
|
|
{:ok, user} ->
|
|
{:ok, _} =
|
|
Accounts.deliver_user_confirmation_instructions(
|
|
user,
|
|
&Routes.user_confirmation_url(conn, :confirm, &1)
|
|
)
|
|
|
|
conn
|
|
|> put_flash(:info, "User created successfully.")
|
|
|> UserAuth.log_in_user(user)
|
|
|
|
{:error, %Ecto.Changeset{} = changeset} ->
|
|
{captcha_text, captcha_result} = Captcha.generate()
|
|
|
|
conn
|
|
|> assign(:captcha, captcha_text)
|
|
|> put_session(:captcha, captcha_result)
|
|
|> render("new.html", changeset: changeset)
|
|
end
|
|
end
|
|
end
|
|
end
|