cannery/lib/lokal_web/controllers/user_registration_controller.ex

81 lines
2.3 KiB
Elixir
Raw Normal View History

2021-03-11 21:12:55 -05:00
defmodule LokalWeb.UserRegistrationController do
use LokalWeb, :controller
2022-02-25 21:53:04 -05:00
import LokalWeb.Gettext
alias Lokal.{Accounts, Invites}
2022-05-05 21:47:22 -04:00
alias LokalWeb.{Endpoint, HomeLive}
2022-02-25 21:53:04 -05:00
def new(conn, %{"invite" => invite_token}) do
invite = Invites.get_invite_by_token(invite_token)
if invite do
conn |> render_new(invite)
else
conn
|> put_flash(:error, dgettext("errors", "Sorry, this invite was not found or expired"))
2022-05-05 21:47:22 -04:00
|> redirect(to: Routes.live_path(Endpoint, HomeLive))
2022-02-25 21:53:04 -05:00
end
end
2021-03-11 21:12:55 -05:00
def new(conn, _params) do
2022-02-25 21:53:04 -05:00
if Accounts.allow_registration?() do
conn |> render_new()
else
conn
|> put_flash(:error, dgettext("errors", "Sorry, public registration is disabled"))
2022-05-05 21:47:22 -04:00
|> redirect(to: Routes.live_path(Endpoint, HomeLive))
2022-02-25 21:53:04 -05:00
end
end
# renders new user registration page
defp render_new(conn, invite \\ nil) do
render(conn, "new.html",
2023-01-29 14:30:42 -05:00
changeset: Accounts.change_user_registration(),
2022-02-25 21:53:04 -05:00
invite: invite,
page_title: gettext("Register")
)
2021-03-11 21:12:55 -05:00
end
2022-02-25 21:53:04 -05:00
def create(conn, %{"user" => %{"invite_token" => invite_token}} = attrs) do
invite = Invites.get_invite_by_token(invite_token)
if invite do
conn |> create_user(attrs, invite)
else
conn
|> put_flash(:error, dgettext("errors", "Sorry, this invite was not found or expired"))
2022-05-05 21:47:22 -04:00
|> redirect(to: Routes.live_path(Endpoint, HomeLive))
2022-02-25 21:53:04 -05:00
end
end
def create(conn, attrs) do
if Accounts.allow_registration?() do
conn |> create_user(attrs)
else
conn
|> put_flash(:error, dgettext("errors", "Sorry, public registration is disabled"))
2022-05-05 21:47:22 -04:00
|> redirect(to: Routes.live_path(Endpoint, HomeLive))
2022-02-25 21:53:04 -05:00
end
end
defp create_user(conn, %{"user" => user_params}, invite \\ nil) do
2021-03-11 21:12:55 -05:00
case Accounts.register_user(user_params) do
{:ok, user} ->
2022-02-25 21:53:04 -05:00
unless invite |> is_nil() do
invite |> Invites.use_invite!()
end
Accounts.deliver_user_confirmation_instructions(
user,
&Routes.user_confirmation_url(conn, :confirm, &1)
)
2021-03-11 21:12:55 -05:00
conn
2022-02-25 21:53:04 -05:00
|> put_flash(:info, dgettext("prompts", "Please check your email to verify your account"))
|> redirect(to: Routes.user_session_path(Endpoint, :new))
2021-03-11 21:12:55 -05:00
{:error, %Ecto.Changeset{} = changeset} ->
2022-02-25 21:53:04 -05:00
conn |> render("new.html", changeset: changeset, invite: invite)
2021-03-11 21:12:55 -05:00
end
end
end