cannery/lib/cannery_web/controllers/user_registration_controller.ex

80 lines
2.4 KiB
Elixir
Raw Normal View History

2021-03-11 21:12:55 -05:00
defmodule CanneryWeb.UserRegistrationController do
use CanneryWeb, :controller
2022-02-09 00:13:01 -05:00
import CanneryWeb.Gettext
alias Cannery.{Accounts, Invites}
2021-03-11 21:12:55 -05:00
alias Cannery.Accounts.User
2022-01-21 20:36:25 -05:00
alias CanneryWeb.{HomeLive, UserAuth}
2021-03-11 21:12:55 -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
2022-02-09 00:13:01 -05:00
|> put_flash(:error, dgettext("errors", "Sorry, this invite was not found or expired"))
2022-01-21 20:36:25 -05:00
|> redirect(to: Routes.live_path(CanneryWeb.Endpoint, HomeLive))
end
end
2021-03-11 21:12:55 -05:00
def new(conn, _params) do
if Accounts.allow_registration?() do
conn |> render_new()
else
conn
2022-02-09 00:13:01 -05:00
|> put_flash(:error, dgettext("errors", "Sorry, public registration is disabled"))
2022-01-21 20:36:25 -05:00
|> redirect(to: Routes.live_path(CanneryWeb.Endpoint, HomeLive))
end
end
# renders new user registration page
defp render_new(conn, invite \\ nil) do
2021-03-11 21:12:55 -05:00
changeset = Accounts.change_user_registration(%User{})
conn |> render("new.html", changeset: changeset, invite: invite)
2021-03-11 21:12:55 -05:00
end
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
2022-02-09 00:13:01 -05:00
|> put_flash(:error, dgettext("errors", "Sorry, this invite was not found or expired"))
2022-01-21 20:36:25 -05:00
|> redirect(to: Routes.live_path(CanneryWeb.Endpoint, HomeLive))
end
end
def create(conn, attrs) do
if Accounts.allow_registration?() do
conn |> create_user(attrs)
else
conn
2022-02-09 00:13:01 -05:00
|> put_flash(:error, dgettext("errors", "Sorry, public registration is disabled"))
2022-01-21 20:36:25 -05:00
|> redirect(to: Routes.live_path(CanneryWeb.Endpoint, HomeLive))
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} ->
unless invite |> is_nil() do
invite |> Invites.use_invite!()
end
2021-03-11 21:12:55 -05:00
{:ok, _} =
Accounts.deliver_user_confirmation_instructions(
user,
&Routes.user_confirmation_url(conn, :confirm, &1)
)
conn
2022-02-09 00:13:01 -05:00
|> put_flash(:info, dgettext("prompts", "User created successfully."))
2021-03-11 21:12:55 -05:00
|> UserAuth.log_in_user(user)
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset, invite: invite)
2021-03-11 21:12:55 -05:00
end
end
end