5.0 KiB · text History 8445167
defmodule CartosnapApp.NeiamAuthAdapter do
  @moduledoc """
  Hands neiam_auth (OIDC) logins to the app's own accounts code.
  Generated by `mix neiam_auth.install --flavour gen_auth_18`.

  Accounts come as in the siblings. Registration is invite-only
  (`CartosnapApp.Accounts.registration_open?/0`), and so is NEIAM:
  `OIDC_PROVISION=invite_only`, with `OIDC_PROVISION_GROUPS` (big-trippr's
  `admins,dads,family,friends`) whose members get an account on their first
  login, through `register_sso_user/1`. Anyone else's first NEIAM login with
  no account to link is refused as not invited and kept pending by
  neiam_auth. If it started from an invite (a
  registration invite or a trip invite: `CartosnapAppWeb.InviteController`
  remembers which), `handle_error/2` sends it back there, where accepting the
  invite makes the account and links the login to it. Otherwise it is told
  to ask for an invite.

  `register_sso_user/1` makes the account for members of
  `OIDC_PROVISION_GROUPS` (and everyone, under `OIDC_PROVISION=auto`): just
  the NEIAM email, confirmed, as a magic-link sign-up's once confirmed. Share links, public
  trips and paired phones are not account sign-ins and are left alone.
  """

  @behaviour NeiamAuth.Adapter

  alias CartosnapApp.Accounts
  alias CartosnapApp.Accounts.User
  alias CartosnapApp.Repo

  import Plug.Conn, only: [get_session: 2]

  @impl true
  def get_user_by_email(email), do: Accounts.get_user_by_email(email)

  @impl true
  def log_in(conn, user) do
    CartosnapAppWeb.UserAuth.log_in_user(conn, user, %{"remember_me" => "true"})
  end

  @impl true
  def current_user(conn) do
    case conn.assigns[:current_scope] do
      %{user: user} -> user
      _ -> nil
    end
  end

  # First login with no account to link: called under PROVISION=auto, and
  # for members of PROVISION_GROUPS (providers with GROUPS_CLAIM) under
  # invite_only too. Creates a passwordless, confirmed user. linkable?/1
  # is not consulted for it. {:error, reason} (a taken handle, say)
  # refuses the login with the generic message; the reason is logged.
  @impl true
  def register_sso_user(%NeiamAuth.Claims{email: email}) when is_binary(email) do
    %User{}
    |> Ecto.Changeset.change(email: email, confirmed_at: DateTime.utc_now(:second))
    |> Ecto.Changeset.unique_constraint(:email)
    |> Repo.insert()
  end

  def register_sso_user(_claims), do: {:error, :no_email}

  # Refuse rows that must never be signed in to by SSO (guest kinds etc.).
  @impl true
  def linkable?(%User{}), do: true

  # Map IdP groups to role flags. Called on every login, only for
  # providers with GROUPS_CLAIM. Manage only the flags you declare here.
  @impl true
  def apply_groups(user, _groups), do: {:ok, user}

  # Who must sign in through SSO: NeiamAuth.password_login_allowed?/1 is
  # false for them, so the password and magic-link paths refuse them.
  # Not consulted when OIDC_LOGIN_MODE is local (or OIDC_ENABLED is off).
  # The library's rule is OIDC_LOGIN_MODE=sso plus a link to a provider
  # with REQUIRED_FOR_LINKED=true. Add the app's own rule with `or`, e.g.
  # admins SSO-only even in mixed:
  #
  #   def sso_required?(user),
  #     do: NeiamAuth.sso_required?(user) or match?(%User{admin: true}, user)
  @impl true
  def sso_required?(user), do: NeiamAuth.sso_required?(user)

  # Refused as not invited, from an invite: back to it, to accept with this
  # login. The address the login brought goes along, for an invite that
  # isn't addressed: neiam_auth's pending entry has it (the identity
  # provider's, so vouched for by it), and link_pending/2 checks the rest.
  @impl true
  def handle_error(conn, :not_invited) do
    keys = CartosnapAppWeb.InviteController.session_keys()

    case {get_session(conn, keys.invite), get_session(conn, keys.trip_invite)} do
      {token, _} when is_binary(token) ->
        conn
        |> back_to_invite(keys.invite_sso, token)
        |> Phoenix.Controller.redirect(to: "/users/register?" <> URI.encode_query(invite: token))

      {_, token} when is_binary(token) ->
        conn
        |> back_to_invite(keys.trip_invite_sso, token)
        |> Phoenix.Controller.redirect(to: "/trips/join/" <> URI.encode(token))

      _ ->
        default_error(conn, :not_invited)
    end
  end

  def handle_error(conn, reason), do: default_error(conn, reason)

  defp back_to_invite(conn, key, token) do
    keys = CartosnapAppWeb.InviteController.session_keys()
    email = get_in(get_session(conn, "neiam_auth_pending") || %{}, ["email"])

    conn
    |> Plug.Conn.put_session(key, token)
    |> Plug.Conn.put_session(keys.sso_email, email)
    |> Phoenix.Controller.put_flash(:info, "Signed in with NEIAM. Accept the invite to finish.")
  end

  # neiam_auth's own behaviour without the callback.
  defp default_error(conn, reason) do
    conn
    |> Phoenix.Controller.put_flash(:error, NeiamAuth.Controller.message(reason))
    |> Phoenix.Controller.redirect(to: login_path())
  end

  @impl true
  def login_path, do: "/users/log-in"

  @impl true
  def settings_path, do: "/users/settings"
end