7.5 KiB · text History 83f70ee
defmodule VigilWeb.Api.V1.AuthController do
  @moduledoc """
  Signing the Android app in (docs/app-login.md). The JSON shapes are
  shared with every NEIAM app, Elixir and Rust alike.

      GET  /api/v1/auth/methods                                  → 200 methods
      POST /api/v1/auth/password  {username_or_email | login, password, device_name}
      POST /api/v1/auth/magic_link  {email}                      → 202, always
      POST /api/v1/auth/magic_link/exchange  {token, device_name}
      POST /api/v1/auth/magic_link/check  {token}   (bearer)     → {valid, same_user}
      POST /api/v1/auth/oidc/exchange  → NeiamAuth.App.ExchangePlug

  A sign-in answers `{token, token_type, user: {id, email}}`; the token is
  the same kind pairing yields: an API token with the Mobile app scopes
  (`Vigil.ApiTokens.issue_app_token/3`), labelled with the device's name,
  listed and revoked on Settings → API tokens, used on `/api/0`.

  Each path makes exactly the web's checks: `NeiamAuth.local_login_enabled?/0`
  (off in `sso_strict`), `NeiamAuth.password_login_allowed?/1` once the
  account is known, the web's own credential and token functions, and the
  same neutral answers. Rate limits are `NeiamAuth.App.rate_limit/3` (not
  the ingest limiter, which is for events). Passwords and tokens are never
  logged (`filter_parameters`). Errors are `{error, message}` and every
  answer is `Cache-Control: no-store`, as the Rust crate's.
  """

  use VigilWeb, :controller

  import NeiamAuth.App, only: [put_no_store: 2]

  plug :put_no_store

  alias NeiamAuth.App
  alias Vigil.{Accounts, ApiTokens}
  alias VigilWeb.UserAuth

  @app_name "Vigil"

  def methods(conn, _params) do
    json(
      conn,
      App.methods(
        app_name: @app_name,
        server: VigilWeb.base_url(),
        mail: Vigil.Mailer.configured?()
      )
    )
  end

  def password(conn, %{"password" => password} = params)
      when is_binary(password) and password != "" do
    # `username_or_email` (the Rust crate's name) or `login`.
    case params["username_or_email"] || params["login"] do
      login when is_binary(login) and login != "" ->
        with :ok <- local_login(conn),
             :ok <- limit(conn, :password, login) do
          # Answered no sooner than 400 ms; User.valid_password?/2 verifies a
          # dummy hash for an unknown email, so neither the time nor the
          # answer tells an unknown email from a wrong password.
          App.with_floor(fn -> check_password(conn, login, password, params) end)
        end

      _ ->
        password(conn, %{})
    end
  end

  def password(conn, _params),
    do: App.json_error(conn, 400, :bad_request, "username_or_email and password are required.")

  defp check_password(conn, login, password, params) do
    user = Accounts.get_user_by_email_and_password(String.trim(login), password)

    cond do
      is_nil(user) ->
        App.json_error(conn, 401, :invalid_credentials, "Invalid email or password.")

      not NeiamAuth.password_login_allowed?(user) ->
        sso_required(conn)

      true ->
        signed_in(conn, user, params["device_name"], :password, %{})
    end
  end

  def magic_link(conn, %{"email" => email}) when is_binary(email) and email != "" do
    with :ok <- local_login(conn),
         :ok <- limit(conn, :magic_link, email) do
      # As the web form: no email for an unknown account or one that must
      # use SSO, and the same answer either way. The link is the web's own
      # (/users/log-in/:token), which the app claims as an App Link.
      user = Accounts.get_user_by_email(String.trim(email))

      if user && NeiamAuth.password_login_allowed?(user) do
        Accounts.deliver_login_instructions(user, &url(~p"/users/log-in/#{&1}"))
      end

      conn
      |> put_status(:accepted)
      |> json(%{
        status: "sent",
        message: "If your email is in our system, you'll receive a sign-in link shortly."
      })
    end
  end

  def magic_link(conn, _params),
    do: App.json_error(conn, 400, :bad_request, "email is required.")

  def magic_link_exchange(conn, %{"token" => token} = params) when is_binary(token) do
    with :ok <- local_login(conn),
         :ok <- limit(conn, :magic_link_exchange, nil) do
      # Checked before the token is spent, as on the web: a refused link
      # stays unused.
      case Accounts.get_user_by_magic_link_token(token) do
        nil ->
          invalid_link(conn)

        user ->
          cond do
            not NeiamAuth.password_login_allowed?(user) ->
              sso_required(conn)

            # phx.gen.auth refuses (raises) here: an unconfirmed account
            # with a password must confirm another way.
            is_nil(user.confirmed_at) and not is_nil(user.hashed_password) ->
              App.json_error(
                conn,
                403,
                :unconfirmed,
                "Confirm this account from the web first, then sign in."
              )

            true ->
              spend_link(conn, token, user, params["device_name"])
          end
      end
    end
  end

  def magic_link_exchange(conn, _params),
    do: App.json_error(conn, 400, :bad_request, "token is required.")

  @doc """
  For a signed-in app that is handed a magic link: whose is it? Never
  spends the token and says nothing about another account but "not you".
  """
  def magic_link_check(%{assigns: %{current_scope: %{user: me}}} = conn, %{"token" => token})
      when is_binary(token) do
    with :ok <- limit(conn, :magic_link_exchange, nil) do
      case Accounts.get_user_by_magic_link_token(token) do
        nil -> json(conn, %{valid: false, same_user: false})
        user -> json(conn, %{valid: true, same_user: user.id == me.id})
      end
    end
  end

  def magic_link_check(%{assigns: %{current_scope: %{user: _}}} = conn, _params),
    do: App.json_error(conn, 400, :bad_request, "token is required.")

  # No Authorization header (VigilWeb.Api.Auth lets that through for
  # /api/0's root; a bad one it refuses itself).
  def magic_link_check(conn, _params),
    do: App.json_error(conn, 401, :unauthorized, "Sign in first.")

  defp spend_link(conn, token, user, device_name) do
    case Accounts.login_user_by_magic_link(token) do
      {:ok, {user_after, tokens_to_disconnect}} ->
        # Confirming an account expires its other sessions, as on the web.
        UserAuth.disconnect_sessions(tokens_to_disconnect)

        signed_in(conn, user_after, device_name, :magic_link, %{
          confirmed: is_nil(user.confirmed_at)
        })

      _ ->
        invalid_link(conn)
    end
  end

  defp signed_in(conn, user, device_name, method, extra) do
    case ApiTokens.issue_app_token(user, App.device_name(device_name), method) do
      {:ok, body} -> json(conn, Map.merge(body, extra))
      {:error, code, message} -> App.json_error(conn, 403, code, message)
    end
  end

  defp local_login(conn) do
    if NeiamAuth.local_login_enabled?(),
      do: :ok,
      else:
        App.json_error(
          conn,
          403,
          :password_login_off,
          "This server only allows Sign in with NEIAM."
        )
  end

  defp limit(conn, action, account) do
    case App.rate_limit(conn, action, account) do
      :ok -> :ok
      {:error, retry_after} -> App.rate_limited(conn, retry_after)
    end
  end

  defp sso_required(conn),
    do:
      App.json_error(
        conn,
        403,
        :refused,
        "This account signs in with NEIAM: use Sign in with NEIAM."
      )

  defp invalid_link(conn),
    do:
      App.json_error(
        conn,
        400,
        :invalid_link,
        "This sign-in link has expired or was already used."
      )
end