Sign in with NEIAM (neiam_auth) and invite-only registration

8445167 · gmorell · 2026-11-24 05:12

54 files +2204 -157
Message
{commit_body(@commit)}

Files changed

modified config/config.exs
+13 −0
@@ -7,6 +7,19 @@
7 7 # General application configuration
8 8 import Config
9 9
10 +# Registration is invite-only, as the sibling apps: a registration invite
11 +# (the Invites page, `mix cartosnap.invite`, the release's `bin/invite`) or
12 +# a trip invite. REGISTRATION_OPEN=true (runtime.exs) lets anyone sign up.
13 +config :cartosnap_app, :registration_open, false
14 +
15 +# "Sign in with NEIAM" (OIDC), as the sibling apps. Inert until
16 +# OIDC_ENABLED=true; providers and the login mode come from OIDC_* env,
17 +# read at start (see the neiam_auth README).
18 +config :neiam_auth,
19 + repo: CartosnapApp.Repo,
20 + user_schema: CartosnapApp.Accounts.User,
21 + adapter: CartosnapApp.NeiamAuthAdapter
22 +
10 23 config :cartosnap_app, :scopes,
11 24 user: [
12 25 default: true,
modified config/runtime.exs
+6 −0
@@ -23,6 +23,12 @@ if public_url = System.get_env("CARTOSNAP_PUBLIC_URL") do
23 23 config :cartosnap_app, :public_url, public_url
24 24 end
25 25
26 +# Invite-only unless REGISTRATION_OPEN=true (config.exs). With NEIAM's
27 +# OIDC_PROVISION=invite_only, a first NEIAM login needs an invite too.
28 +if registration_open = System.get_env("REGISTRATION_OPEN") do
29 + config :cartosnap_app, :registration_open, registration_open in ~w(true 1)
30 +end
31 +
26 32 if System.get_env("PHX_SERVER") do
27 33 config :cartosnap_app, CartosnapAppWeb.Endpoint, server: true
28 34 end
modified config/test.exs
+3 −0
@@ -1,5 +1,8 @@
1 1 import Config
2 2
3 +# Tests assume open registration unless they opt out (registration_invite_test).
4 +config :cartosnap_app, :registration_open, true
5 +
3 6 # Only in tests, remove the complexity from the password hashing algorithm
4 7 config :bcrypt_elixir, :log_rounds, 1
5 8
modified lib/cartosnap_app/accounts.ex
+205 −1
@@ -6,7 +6,7 @@ defmodule CartosnapApp.Accounts do
6 6 import Ecto.Query, warn: false
7 7 alias CartosnapApp.Repo
8 8
9 − alias CartosnapApp.Accounts.{User, UserToken, UserNotifier}
9 + alias CartosnapApp.Accounts.{Invite, User, UserToken, UserNotifier}
10 10
11 11 ## Names
12 12
@@ -106,6 +106,210 @@ defmodule CartosnapApp.Accounts do
106 106 |> Repo.insert()
107 107 end
108 108
109 + ## Registration invites
110 +
111 + @doc """
112 + Whether anyone may make an account. When false (the default, as the
113 + sibling apps), registration needs an invite: a registration invite
114 + (`CartosnapApp.Accounts.Invite`) or a trip invite. `REGISTRATION_OPEN=true`
115 + opens it.
116 + """
117 + @spec registration_open?() :: boolean()
118 + def registration_open? do
119 + Application.get_env(:cartosnap_app, :registration_open, false) == true
120 + end
121 +
122 + @doc """
123 + Creates a registration invite, owned by `owner`, or by nobody when `owner`
124 + is nil (the very first invite, from the command line).
125 +
126 + `attrs` may carry `:note`, `:email` (to address it to one person) and
127 + `:expires_at`, or `:days` to expire that many days from now.
128 +
129 + The returned invite carries its raw link `token`, the only time it exists.
130 + """
131 + def create_invite(owner, attrs \\ %{}) do
132 + attrs = Map.new(attrs)
133 +
134 + expires_at =
135 + case attrs[:days] do
136 + days when is_integer(days) and days > 0 ->
137 + DateTime.utc_now(:second) |> DateTime.add(days, :day)
138 +
139 + _ ->
140 + attrs[:expires_at]
141 + end
142 +
143 + attrs =
144 + attrs
145 + |> Map.take([:note, :email])
146 + |> Map.reject(fn {_k, v} -> v in [nil, ""] end)
147 + |> Map.put(:expires_at, expires_at)
148 + |> Map.put(:created_by_id, owner && owner.id)
149 +
150 + %Invite{}
151 + |> Invite.create_changeset(attrs)
152 + |> Repo.insert()
153 + end
154 +
155 + @doc """
156 + The command-line way in, shared by `mix cartosnap.invite` and the
157 + release's `bin/invite`: `opts` are `:email` (whom it is for), `:note`,
158 + `:days` and `:by` (an owner's email).
159 + """
160 + def create_invite_from_cli(opts) do
161 + owner =
162 + case opts[:by] do
163 + nil ->
164 + {:ok, nil}
165 +
166 + email ->
167 + if user = get_user_by_email(email), do: {:ok, user}, else: {:error, :no_such_user}
168 + end
169 +
170 + with {:ok, owner} <- owner do
171 + create_invite(owner, Map.take(Map.new(opts), [:email, :note, :days]))
172 + end
173 + end
174 +
175 + @doc "Registration invites a user made, newest first, with who used them."
176 + def list_invites(%User{id: id}) do
177 + from(i in Invite,
178 + where: i.created_by_id == ^id,
179 + order_by: [desc: i.inserted_at],
180 + preload: [:consumed_by]
181 + )
182 + |> Repo.all()
183 + end
184 +
185 + @doc "The registration invite a link's raw token names, if it can still be used."
186 + def get_active_invite(token) when is_binary(token) and token != "" do
187 + case Repo.get_by(Invite, token_hash: Invite.hash_token(token)) do
188 + nil -> nil
189 + invite -> if Invite.active?(invite), do: invite
190 + end
191 + end
192 +
193 + def get_active_invite(_), do: nil
194 +
195 + @doc """
196 + Registers from an unaddressed registration invite, by email (confirmed
197 + later by magic link, as open registration), and spends the invite in the
198 + same transaction, so one link can't make two accounts.
199 + `{:error, :invite_used}` when it went in the meantime.
200 + """
201 + def register_user_with_invite(attrs, token) do
202 + Repo.transact(fn ->
203 + with %Invite{} = invite <- lock_active_invite(token) || {:error, :invite_used},
204 + {:ok, user} <- register_user(attrs),
205 + {:ok, _} <- consume_invite(invite, user) do
206 + {:ok, user}
207 + end
208 + end)
209 + end
210 +
211 + @doc """
212 + Makes the account a registration invite is for, confirmed, and spends the
213 + invite, in one transaction: `{:ok, user}`, and the caller signs them in.
214 +
215 + The address is the invite's own when it is addressed. Otherwise it must
216 + be given (`email`): the one a NEIAM login brought, which the identity
217 + provider vouches for. A bare unaddressed link proves no address, so the
218 + local way with one is `register_user_with_invite/2`.
219 +
220 + Refuses `{:error, :has_account}` when the address already has an account:
221 + an invite must never sign anyone in to an existing account, or addressing
222 + an invite to someone would hand theirs over. `{:error, :invalid}` for a
223 + spent or expired invite, or no address to use.
224 + """
225 + def register_by_invite(token, email \\ nil)
226 +
227 + def register_by_invite(token, email) when is_binary(token) do
228 + Repo.transact(fn ->
229 + invite = lock_active_invite(token)
230 + email = invite && (invite.email || email)
231 +
232 + cond do
233 + is_nil(invite) or not is_binary(email) -> {:error, :invalid}
234 + get_user_by_email(email) -> {:error, :has_account}
235 + true -> with {:ok, user} <- register_confirmed_user(email), do: consume(invite, user)
236 + end
237 + end)
238 + end
239 +
240 + def register_by_invite(_, _), do: {:error, :invalid}
241 +
242 + defp consume(invite, user) do
243 + with {:ok, _} <- consume_invite(invite, user), do: {:ok, user}
244 + end
245 +
246 + # Locked, so two submits of one link can't both spend it.
247 + defp lock_active_invite(token) when is_binary(token) do
248 + query =
249 + from(i in Invite, where: i.token_hash == ^Invite.hash_token(token), lock: "FOR UPDATE")
250 +
251 + case Repo.one(query) do
252 + %Invite{} = invite -> if Invite.active?(invite), do: invite
253 + nil -> nil
254 + end
255 + end
256 +
257 + defp lock_active_invite(_), do: nil
258 +
259 + @doc "Marks a registration invite as consumed by the given user."
260 + def consume_invite(%Invite{} = invite, %User{} = user) do
261 + invite |> Invite.consume_changeset(user) |> Repo.update()
262 + end
263 +
264 + @doc """
265 + Gives one of `owner`'s active invites a new token, so any earlier copy of
266 + the link stops working. The returned invite carries the new raw `token`,
267 + to show once. Anyone else's, or a spent one, is `{:error, :not_found}`.
268 + """
269 + def rotate_invite(%User{id: owner_id}, invite_id) do
270 + with {:ok, invite_id} <- Ecto.UUID.cast(invite_id),
271 + %Invite{} = invite <- Repo.get_by(Invite, id: invite_id, created_by_id: owner_id),
272 + true <- Invite.active?(invite),
273 + {:ok, invite} <- invite |> Invite.rotate_token_changeset() |> Repo.update() do
274 + {:ok, Repo.preload(invite, :consumed_by)}
275 + else
276 + _ -> {:error, :not_found}
277 + end
278 + end
279 +
280 + @doc """
281 + The command-line way to a fresh link for the newest active invite
282 + addressed to `email` (whoever owns it): rotates its token, so earlier
283 + links stop working. `{:error, :not_found}` when there is none.
284 + """
285 + def rotate_invite_for_email(email) when is_binary(email) do
286 + from(i in Invite,
287 + where: i.email == ^(email |> String.trim() |> String.downcase()) and is_nil(i.consumed_at),
288 + order_by: [desc: i.inserted_at]
289 + )
290 + |> Repo.all()
291 + |> Enum.find(&Invite.active?/1)
292 + |> case do
293 + nil -> {:error, :not_found}
294 + invite -> invite |> Invite.rotate_token_changeset() |> Repo.update()
295 + end
296 + end
297 +
298 + @doc "Revokes one of `owner`'s unused invites. Anyone else's, or a missing one, is `{:error, :not_found}`."
299 + def revoke_invite(%User{id: owner_id}, invite_id) do
300 + with {:ok, invite_id} <- Ecto.UUID.cast(invite_id),
301 + %Invite{consumed_at: nil} = invite <-
302 + Repo.get_by(Invite, id: invite_id, created_by_id: owner_id),
303 + {:ok, invite} <-
304 + invite
305 + |> Ecto.Changeset.change(consumed_at: DateTime.utc_now(:second))
306 + |> Repo.update() do
307 + {:ok, Repo.preload(invite, :consumed_by)}
308 + else
309 + _ -> {:error, :not_found}
310 + end
311 + end
312 +
109 313 ## Settings
110 314
111 315 @doc """
added lib/cartosnap_app/accounts/invite.ex
+92 −0
@@ -0,0 +1,92 @@
1 +defmodule CartosnapApp.Accounts.Invite do
2 + @moduledoc """
3 + A single-use registration invite, as the sibling apps. While registration
4 + is closed (`CartosnapApp.Accounts.registration_open?/0`, the default),
5 + `/users/register` only takes a visitor carrying a valid invite: one of
6 + these in the URL, or a trip invite (`CartosnapApp.Trips.TripInvite`).
7 +
8 + An invite may be addressed to an `email`. Then the link is for that
9 + person only: the account is made for that address, already confirmed
10 + (holding the link stands in for the confirmation email), and they're
11 + signed in. An unaddressed invite proves nothing about an address: whoever
12 + holds it picks an email and confirms it by magic link, as with open
13 + registration.
14 +
15 + With NEIAM on and `OIDC_PROVISION=invite_only`, an invite is also how a
16 + first NEIAM login gets an account (`CartosnapAppWeb.InviteController`).
17 +
18 + Only a SHA-256 of the token is stored (`token_hash`). The raw token is in
19 + the link alone, and on the struct (the virtual `token`) only as it comes
20 + back from creating or rotating, which is the one time to show the link.
21 + """
22 + use Ecto.Schema
23 + import Ecto.Changeset
24 +
25 + alias CartosnapApp.Accounts.User
26 +
27 + @primary_key {:id, :binary_id, autogenerate: true}
28 + @foreign_key_type :binary_id
29 + schema "user_invites" do
30 + field :token, :string, virtual: true, redact: true
31 + field :token_hash, :binary, redact: true
32 + field :note, :string
33 + field :email, :string
34 + field :expires_at, :utc_datetime
35 + field :consumed_at, :utc_datetime
36 +
37 + belongs_to :created_by, User
38 + belongs_to :consumed_by, User
39 +
40 + timestamps(type: :utc_datetime)
41 + end
42 +
43 + @doc false
44 + def create_changeset(invite, attrs) do
45 + invite
46 + |> cast(attrs, [:note, :email, :created_by_id, :expires_at])
47 + |> update_change(:email, &(&1 |> String.trim() |> String.downcase()))
48 + |> put_new_token()
49 + |> validate_length(:note, max: 200)
50 + |> validate_format(:email, ~r/^[^@,;\s]+@[^@,;\s]+$/,
51 + message: "must have the @ sign and no spaces"
52 + )
53 + |> validate_length(:email, max: 160)
54 + |> unique_constraint(:token_hash)
55 + end
56 +
57 + @doc """
58 + Stamps the invite as consumed by the given user. Idempotent: a second
59 + call returns the same record without re-stamping.
60 + """
61 + def consume_changeset(invite, %User{id: user_id}) do
62 + if invite.consumed_at,
63 + do: change(invite),
64 + else: change(invite, consumed_at: DateTime.utc_now(:second), consumed_by_id: user_id)
65 + end
66 +
67 + @doc "A new token, so every earlier link to this invite stops working."
68 + def rotate_token_changeset(invite), do: invite |> change() |> put_new_token()
69 +
70 + @doc "A new link token: `{raw, hash}`. Only the hash is stored."
71 + def build_token do
72 + raw = :crypto.strong_rand_bytes(24) |> Base.url_encode64(padding: false)
73 + {raw, hash_token(raw)}
74 + end
75 +
76 + @doc "The stored form of a link token."
77 + def hash_token(raw) when is_binary(raw), do: :crypto.hash(:sha256, raw)
78 +
79 + @doc "True when the invite can still be used: not consumed (or revoked), not expired."
80 + @spec active?(%__MODULE__{}) :: boolean()
81 + def active?(%__MODULE__{consumed_at: nil, expires_at: nil}), do: true
82 +
83 + def active?(%__MODULE__{consumed_at: nil, expires_at: %DateTime{} = exp}),
84 + do: DateTime.after?(exp, DateTime.utc_now())
85 +
86 + def active?(_), do: false
87 +
88 + defp put_new_token(changeset) do
89 + {raw, hash} = build_token()
90 + changeset |> put_change(:token, raw) |> put_change(:token_hash, hash)
91 + end
92 +end
modified lib/cartosnap_app/application.ex
+2 −0

Click to load diff…

added lib/cartosnap_app/neiam_auth_adapter.ex
+132 −0

Click to load diff…

modified lib/cartosnap_app/release.ex
+90 −0

Click to load diff…

modified lib/cartosnap_app/trips.ex
+55 −16

Click to load diff…

modified lib/cartosnap_app_web.ex
+27 −0

Click to load diff…

modified lib/cartosnap_app_web/components/layouts.ex
+2 −1

Click to load diff…

modified lib/cartosnap_app_web/controllers/invite_controller.ex
+217 −4

Click to load diff…

added lib/cartosnap_app_web/controllers/neiam_auth_controller.ex
+3 −0

Click to load diff…

modified lib/cartosnap_app_web/controllers/user_session_controller.ex
+46 −20

Click to load diff…

modified lib/cartosnap_app_web/live/home_live.ex
+6 −1

Click to load diff…

modified lib/cartosnap_app_web/live/trip_live/join.ex
+72 −7

Click to load diff…

modified lib/cartosnap_app_web/live/user_live/invites.ex
+224 −4

Click to load diff…

modified lib/cartosnap_app_web/live/user_live/login.ex
+88 −66

Click to load diff…

modified lib/cartosnap_app_web/live/user_live/registration.ex
+276 −37

Click to load diff…

modified lib/cartosnap_app_web/live/user_live/settings.ex
+7 −0

Click to load diff…

modified lib/cartosnap_app_web/router.ex
+17 −0

Click to load diff…

added lib/mix/tasks/cartosnap.invite.ex
+52 −0

Click to load diff…

added lib/mix/tasks/cartosnap.invite.link.ex
+33 −0

Click to load diff…

modified mix.exs
+4 −0

Click to load diff…

modified mix.lock
+4 −0

Click to load diff…

added priv/repo/migrations/20261124021745_create_neiam_auth_identities.exs
+27 −0

Click to load diff…

added priv/repo/migrations/20261124045538_create_user_invites.exs
+25 −0

Click to load diff…

added rel/overlays/bin/invite
+24 −0

Click to load diff…

added rel/overlays/bin/invite-link
+11 −0

Click to load diff…

added test/cartosnap_app_web/controllers/neiam_auth_test.exs
+314 −0

Click to load diff…

added test/cartosnap_app_web/live/user_live/registration_invite_test.exs
+127 −0

Click to load diff…

Parents: 44bc4f7