commit 723eb8a0abe9c89d60afa4518f91a4a161fa17b9
parent 870f09ed6f3dcb7b4876188577a9f0fcc52df565
Author: Gabriel G. de Brito <me@gboncoffee.dev.br>
Date: Thu, 19 Nov 2026 15:09:13 -0300
Add users service in Phoenix.
JSON-only Phoenix app that keeps the list of user names and delegates
credentials to the auth service:
- POST /users stores the name (the only column) and creates the
credentials in auth inside a transaction, rolled back if auth fails.
Answers 201, 409 for a taken name, 422 for invalid fields and 502/503
for auth errors.
- POST /login relays the auth service response unchanged.
The auth service URL comes from SIGA_AUTH_URL (default
http://localhost:8080). Tests stub auth with Req.Test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
38 files changed, 1215 insertions(+), 0 deletions(-)
diff --git a/users/.formatter.exs b/users/.formatter.exs
@@ -0,0 +1,5 @@
+[
+ import_deps: [:ecto, :ecto_sql, :phoenix],
+ subdirectories: ["priv/*/migrations"],
+ inputs: ["*.{ex,exs}", "{config,lib,test}/**/*.{ex,exs}", "priv/*/seeds.exs"]
+]
diff --git a/users/.gitignore b/users/.gitignore
@@ -0,0 +1,31 @@
+# The directory Mix will write compiled artifacts to.
+/_build/
+
+# If you run "mix test --cover", coverage assets end up here.
+/cover/
+
+# The directory Mix downloads your dependencies sources to.
+/deps/
+
+# Where 3rd-party dependencies like ExDoc output generated docs.
+/doc/
+
+# Ignore .fetch files in case you like to edit your project deps locally.
+/.fetch
+
+# If the VM crashes, it generates a dump, let's ignore it too.
+erl_crash.dump
+
+# Also ignore archive artifacts (built via "mix archive.build").
+*.ez
+
+# Temporary files, for example, from tests.
+/tmp/
+
+# Ignore package tarball (built via "mix hex.build").
+users-*.tar
+
+# Database files
+*.db
+*.db-*
+
diff --git a/users/README.md b/users/README.md
@@ -0,0 +1,38 @@
+# users
+
+Serviço de usuários do SIGA, em Elixir com Phoenix (só API JSON).
+
+Guarda apenas a lista de nomes. As senhas ficam no serviço `auth`, que é
+chamado na criação e no login.
+
+## Rotas
+
+| Rota | Corpo | Resposta |
+|---|---|---|
+| `POST /users` | `{"name": "...", "password": "..."}` | 201 `{"name": "..."}`; 409 nome em uso; 422 campos inválidos; 502/503 erro no auth |
+| `POST /login` | `{"name": "...", "password": "..."}` | a resposta do `POST /login` do auth, sem alterações; 400 sem nome ou senha; 503 auth fora do ar |
+
+Na criação, o nome é gravado numa transação que é desfeita se o auth não
+aceitar as credenciais.
+
+## Rodando
+
+```sh
+mix setup # dependências e banco
+SIGA_AUTH_URL=http://localhost:8080 PORT=4000 mix phx.server
+mix test
+```
+
+| Variável | Padrão |
+|---|---|
+| `PORT` | `4000` |
+| `SIGA_AUTH_URL` | `http://localhost:8080` |
+| `DATABASE_PATH` | obrigatória em produção |
+
+## Estrutura (MVC)
+
+- Model: `lib/users/accounts/user.ex` (schema e validações) e o contexto
+ `lib/users/accounts.ex`.
+- Cliente do auth: `lib/users/auth.ex`.
+- Controllers: `lib/users_web/controllers/{user,session,fallback}_controller.ex`.
+- Views: `lib/users_web/controllers/{user,changeset,error}_json.ex`.
diff --git a/users/config/config.exs b/users/config/config.exs
@@ -0,0 +1,38 @@
+# This file is responsible for configuring your application
+# and its dependencies with the aid of the Config module.
+#
+# This configuration file is loaded before any dependency and
+# is restricted to this project.
+
+# General application configuration
+import Config
+
+config :users,
+ ecto_repos: [Users.Repo],
+ generators: [timestamp_type: :utc_datetime]
+
+# Configure the endpoint
+config :users, UsersWeb.Endpoint,
+ url: [host: "localhost"],
+ adapter: Bandit.PhoenixAdapter,
+ render_errors: [
+ formats: [json: UsersWeb.ErrorJSON],
+ layout: false
+ ],
+ pubsub_server: Users.PubSub,
+ live_view: [signing_salt: "cLrzQwXm"]
+
+# Configure Elixir's Logger
+config :logger, :default_formatter,
+ format: "$time $metadata[$level] $message\n",
+ metadata: [:request_id]
+
+# Use Jason for JSON parsing in Phoenix
+config :phoenix, :json_library, Jason
+
+# Base URL of the SIGA auth service. Overridden by SIGA_AUTH_URL at runtime.
+config :users, :auth_url, "http://localhost:8080"
+
+# Import environment specific config. This must remain at the bottom
+# of this file so it overrides the configuration defined above.
+import_config "#{config_env()}.exs"
diff --git a/users/config/dev.exs b/users/config/dev.exs
@@ -0,0 +1,60 @@
+import Config
+
+# Configure your database
+config :users, Users.Repo,
+ database: Path.expand("../users_dev.db", __DIR__),
+ pool_size: 5,
+ stacktrace: true,
+ show_sensitive_data_on_connection_error: true
+
+# For development, we disable any cache and enable
+# debugging and code reloading.
+#
+# The watchers configuration can be used to run external
+# watchers to your application. For example, we can use it
+# to bundle .js and .css sources.
+config :users, UsersWeb.Endpoint,
+ # Binding to loopback ipv4 address prevents access from other machines.
+ # Change to `ip: {0, 0, 0, 0}` to allow access from other machines.
+ http: [ip: {127, 0, 0, 1}],
+ check_origin: false,
+ code_reloader: true,
+ debug_errors: true,
+ secret_key_base: "kBmN5uKksyVmKceO2I7skqXx+Ger9wSpW3XAb1H4laE3N2EXVUQSlFtnxRM1kecJ",
+ watchers: []
+
+# ## SSL Support
+#
+# In order to use HTTPS in development, a self-signed
+# certificate can be generated by running the following
+# Mix task:
+#
+# mix phx.gen.cert
+#
+# Run `mix help phx.gen.cert` for more information.
+#
+# The `http:` config above can be replaced with:
+#
+# https: [
+# port: 4001,
+# cipher_suite: :strong,
+# keyfile: "priv/cert/selfsigned_key.pem",
+# certfile: "priv/cert/selfsigned.pem"
+# ],
+#
+# If desired, both `http:` and `https:` keys can be
+# configured to run both http and https servers on
+# different ports.
+
+# Enable dev routes for dashboard and mailbox
+config :users, dev_routes: true
+
+# Do not include metadata nor timestamps in development logs
+config :logger, :default_formatter, format: "[$level] $message\n"
+
+# Set a higher stacktrace during development. Avoid configuring such
+# in production as building large stacktraces may be expensive.
+config :phoenix, :stacktrace_depth, 20
+
+# Initialize plugs at runtime for faster development compilation
+config :phoenix, :plug_init_mode, :runtime
diff --git a/users/config/prod.exs b/users/config/prod.exs
@@ -0,0 +1,19 @@
+import Config
+
+# Force using SSL in production. This also sets the "strict-security-transport" header,
+# known as HSTS. If you have a health check endpoint, you may want to exclude it below.
+# Note `:force_ssl` is required to be set at compile-time.
+config :users, UsersWeb.Endpoint,
+ force_ssl: [
+ rewrite_on: [:x_forwarded_proto],
+ exclude: [
+ # paths: ["/health"],
+ hosts: ["localhost", "127.0.0.1"]
+ ]
+ ]
+
+# Do not print debug messages in production
+config :logger, level: :info
+
+# Runtime production configuration, including reading
+# of environment variables, is done on config/runtime.exs.
diff --git a/users/config/runtime.exs b/users/config/runtime.exs
@@ -0,0 +1,99 @@
+import Config
+
+# config/runtime.exs is executed for all environments, including
+# during releases. It is executed after compilation and before the
+# system starts, so it is typically used to load production configuration
+# and secrets from environment variables or elsewhere. Do not define
+# any compile-time configuration in here, as it won't be applied.
+# The block below contains prod specific runtime configuration.
+
+# ## Using releases
+#
+# If you use `mix release`, you need to explicitly enable the server
+# by passing the PHX_SERVER=true when you start it:
+#
+# PHX_SERVER=true bin/users start
+#
+# Alternatively, you can use `mix phx.gen.release` to generate a `bin/server`
+# script that automatically sets the env var above.
+if System.get_env("PHX_SERVER") do
+ config :users, UsersWeb.Endpoint, server: true
+end
+
+config :users, UsersWeb.Endpoint, http: [port: String.to_integer(System.get_env("PORT", "4000"))]
+
+if auth_url = System.get_env("SIGA_AUTH_URL") do
+ config :users, :auth_url, auth_url
+end
+
+if config_env() == :prod do
+ database_path =
+ System.get_env("DATABASE_PATH") ||
+ raise """
+ environment variable DATABASE_PATH is missing.
+ For example: /etc/users/users.db
+ """
+
+ config :users, Users.Repo,
+ database: database_path,
+ pool_size: String.to_integer(System.get_env("POOL_SIZE") || "5")
+
+ # The secret key base is used to sign/encrypt cookies and other secrets.
+ # A default value is used in config/dev.exs and config/test.exs but you
+ # want to use a different value for prod and you most likely don't want
+ # to check this value into version control, so we use an environment
+ # variable instead.
+ secret_key_base =
+ System.get_env("SECRET_KEY_BASE") ||
+ raise """
+ environment variable SECRET_KEY_BASE is missing.
+ You can generate one by calling: mix phx.gen.secret
+ """
+
+ host = System.get_env("PHX_HOST") || "example.com"
+
+ config :users, :dns_cluster_query, System.get_env("DNS_CLUSTER_QUERY")
+
+ config :users, UsersWeb.Endpoint,
+ url: [host: host, port: 443, scheme: "https"],
+ http: [
+ # Enable IPv6 and bind on all interfaces.
+ # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
+ # See the documentation on https://bandit.hexdocs.pm/Bandit.html#t:options/0
+ # for details about using IPv6 vs IPv4 and loopback vs public addresses.
+ ip: {0, 0, 0, 0, 0, 0, 0, 0}
+ ],
+ secret_key_base: secret_key_base
+
+ # ## SSL Support
+ #
+ # To get SSL working, you will need to add the `https` key
+ # to your endpoint configuration:
+ #
+ # config :users, UsersWeb.Endpoint,
+ # https: [
+ # ...,
+ # port: 443,
+ # cipher_suite: :strong,
+ # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
+ # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
+ # ]
+ #
+ # The `cipher_suite` is set to `:strong` to support only the
+ # latest and more secure SSL ciphers. This means old browsers
+ # and clients may not be supported. You can set it to
+ # `:compatible` for wider support.
+ #
+ # `:keyfile` and `:certfile` expect an absolute path to the key
+ # and cert in disk or a relative path inside priv, for example
+ # "priv/ssl/server.key". For all supported SSL configuration
+ # options, see https://plug.hexdocs.pm/Plug.SSL.html#configure/1
+ #
+ # We also recommend setting `force_ssl` in your config/prod.exs,
+ # ensuring no data is ever sent via http, always redirecting to https:
+ #
+ # config :users, UsersWeb.Endpoint,
+ # force_ssl: [hsts: true]
+ #
+ # Check `Plug.SSL` for all available options in `force_ssl`.
+end
diff --git a/users/config/test.exs b/users/config/test.exs
@@ -0,0 +1,31 @@
+import Config
+
+# Configure your database
+#
+# The MIX_TEST_PARTITION environment variable can be used
+# to provide built-in test partitioning in CI environment.
+# Run `mix help test` for more information.
+config :users, Users.Repo,
+ database: Path.expand("../users_test.db", __DIR__),
+ pool_size: 5,
+ pool: Ecto.Adapters.SQL.Sandbox
+
+# We don't run a server during test. If one is required,
+# you can enable the server option below.
+config :users, UsersWeb.Endpoint,
+ http: [ip: {127, 0, 0, 1}, port: 4002],
+ secret_key_base: "RkNflWf8t1qfz56I7hDhjmpZ11LFrgep/RqKCA+hk9O8EGRz4vSjTJOjmJZXaIDE",
+ server: false
+
+# Print only warnings and errors during test
+config :logger, level: :warning
+
+# Initialize plugs at runtime for faster test compilation
+config :phoenix, :plug_init_mode, :runtime
+
+# Sort query params output of verified routes for robust url comparisons
+config :phoenix,
+ sort_verified_routes_query_params: true
+
+# Requests to the auth service are answered by Req.Test stubs.
+config :users, :auth_req_options, plug: {Req.Test, Users.Auth}
diff --git a/users/lib/users.ex b/users/lib/users.ex
@@ -0,0 +1,9 @@
+defmodule Users do
+ @moduledoc """
+ Users keeps the contexts that define your domain
+ and business logic.
+
+ Contexts are also responsible for managing your data, regardless
+ if it comes from the database, an external API or others.
+ """
+end
diff --git a/users/lib/users/accounts.ex b/users/lib/users/accounts.ex
@@ -0,0 +1,32 @@
+defmodule Users.Accounts do
+ @moduledoc """
+ User accounts. Names are stored here; credentials live in the auth service.
+ """
+ alias Users.Accounts.User
+ alias Users.Auth
+ alias Users.Repo
+
+ @doc """
+ Creates a user and its credentials in the auth service.
+
+ The name is inserted inside a transaction that is rolled back if the auth
+ service does not accept the credentials, so both sides stay in sync.
+ """
+ @spec create_user(map()) ::
+ {:ok, User.t()}
+ | {:error, Ecto.Changeset.t()}
+ | {:error, :auth_rejected | :auth_unavailable}
+ def create_user(attrs) do
+ changeset = User.registration_changeset(%User{}, attrs)
+
+ Repo.transact(fn ->
+ with {:ok, user} <- Repo.insert(changeset),
+ :ok <- Auth.create_credentials(user.name, user.password) do
+ {:ok, %{user | password: nil}}
+ end
+ end)
+ end
+
+ @doc "Logs a user in. Relays the auth service response as is."
+ defdelegate login(name, password), to: Auth
+end
diff --git a/users/lib/users/accounts/user.ex b/users/lib/users/accounts/user.ex
@@ -0,0 +1,24 @@
+defmodule Users.Accounts.User do
+ @moduledoc """
+ A SIGA user. Only the name is stored; the password is a virtual field that
+ is validated here and handed to the auth service, never persisted.
+ """
+ use Ecto.Schema
+ import Ecto.Changeset
+
+ @max_name_length 64
+
+ @primary_key {:name, :string, autogenerate: false}
+ schema "users" do
+ field :password, :string, virtual: true, redact: true
+ end
+
+ @doc "Changeset for creating a user with a name and a password."
+ def registration_changeset(user, attrs) do
+ user
+ |> cast(attrs, [:name, :password])
+ |> validate_required([:name, :password])
+ |> validate_length(:name, max: @max_name_length)
+ |> unique_constraint(:name, message: "has already been taken")
+ end
+end
diff --git a/users/lib/users/application.ex b/users/lib/users/application.ex
@@ -0,0 +1,41 @@
+defmodule Users.Application do
+ # See https://elixir.hexdocs.pm/Application.html
+ # for more information on OTP Applications
+ @moduledoc false
+
+ use Application
+
+ @impl true
+ def start(_type, _args) do
+ children = [
+ UsersWeb.Telemetry,
+ Users.Repo,
+ {Ecto.Migrator,
+ repos: Application.fetch_env!(:users, :ecto_repos), skip: skip_migrations?()},
+ {DNSCluster, query: Application.get_env(:users, :dns_cluster_query) || :ignore},
+ {Phoenix.PubSub, name: Users.PubSub},
+ # Start a worker by calling: Users.Worker.start_link(arg)
+ # {Users.Worker, arg},
+ # Start to serve requests, typically the last entry
+ UsersWeb.Endpoint
+ ]
+
+ # See https://elixir.hexdocs.pm/Supervisor.html
+ # for other strategies and supported options
+ opts = [strategy: :one_for_one, name: Users.Supervisor]
+ Supervisor.start_link(children, opts)
+ end
+
+ # Tell Phoenix to update the endpoint configuration
+ # whenever the application is updated.
+ @impl true
+ def config_change(changed, _new, removed) do
+ UsersWeb.Endpoint.config_change(changed, removed)
+ :ok
+ end
+
+ defp skip_migrations?() do
+ # By default, sqlite migrations are run when using a release
+ System.get_env("RELEASE_NAME") == nil
+ end
+end
diff --git a/users/lib/users/auth.ex b/users/lib/users/auth.ex
@@ -0,0 +1,59 @@
+defmodule Users.Auth do
+ @moduledoc """
+ HTTP client for the SIGA auth service (`auth/`, written in Go).
+
+ The base URL comes from the `:auth_url` application environment
+ (`SIGA_AUTH_URL` at runtime). Extra `Req` options, such as a test plug,
+ can be set in `:auth_req_options`.
+ """
+ require Logger
+
+ @doc "Registers the credentials of a user in the auth service."
+ @spec create_credentials(String.t(), String.t()) ::
+ :ok | {:error, :auth_rejected | :auth_unavailable}
+ def create_credentials(name, password) do
+ case post("/credentials", name, password) do
+ {:ok, %Req.Response{status: 200}} ->
+ :ok
+
+ {:ok, %Req.Response{status: status, body: body}} ->
+ Logger.error("auth: POST /credentials answered #{status}: #{inspect(body)}")
+ {:error, :auth_rejected}
+
+ {:error, exception} ->
+ Logger.error("auth: POST /credentials failed: #{Exception.message(exception)}")
+ {:error, :auth_unavailable}
+ end
+ end
+
+ @doc """
+ Logs in through the auth service. Returns its response untouched, whatever
+ the status, so it can be relayed to the client.
+ """
+ @spec login(String.t(), String.t()) :: {:ok, Req.Response.t()} | {:error, :auth_unavailable}
+ def login(name, password) do
+ case post("/login", name, password) do
+ {:ok, response} ->
+ {:ok, response}
+
+ {:error, exception} ->
+ Logger.error("auth: POST /login failed: #{Exception.message(exception)}")
+ {:error, :auth_unavailable}
+ end
+ end
+
+ defp post(path, name, password) do
+ [
+ method: :post,
+ base_url: Application.fetch_env!(:users, :auth_url),
+ url: path,
+ json: %{"Username" => name, "Password" => password},
+ decode_body: false,
+ retry: false,
+ receive_timeout: 5_000
+ ]
+ |> Req.new()
+ |> Req.merge(Application.get_env(:users, :auth_req_options, []))
+ |> Req.request()
+ end
+end
diff --git a/users/lib/users/repo.ex b/users/lib/users/repo.ex
@@ -0,0 +1,5 @@
+defmodule Users.Repo do
+ use Ecto.Repo,
+ otp_app: :users,
+ adapter: Ecto.Adapters.SQLite3
+end
diff --git a/users/lib/users_web.ex b/users/lib/users_web.ex
@@ -0,0 +1,63 @@
+defmodule UsersWeb do
+ @moduledoc """
+ The entrypoint for defining your web interface, such
+ as controllers, components, channels, and so on.
+
+ This can be used in your application as:
+
+ use UsersWeb, :controller
+ use UsersWeb, :html
+
+ The definitions below will be executed for every controller,
+ component, etc, so keep them short and clean, focused
+ on imports, uses and aliases.
+
+ Do NOT define functions inside the quoted expressions
+ below. Instead, define additional modules and import
+ those modules here.
+ """
+
+ def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)
+
+ def router do
+ quote do
+ use Phoenix.Router, helpers: false
+
+ # Import common connection and controller functions to use in pipelines
+ import Plug.Conn
+ import Phoenix.Controller
+ end
+ end
+
+ def channel do
+ quote do
+ use Phoenix.Channel
+ end
+ end
+
+ def controller do
+ quote do
+ use Phoenix.Controller, formats: [:html, :json]
+
+ import Plug.Conn
+
+ unquote(verified_routes())
+ end
+ end
+
+ def verified_routes do
+ quote do
+ use Phoenix.VerifiedRoutes,
+ endpoint: UsersWeb.Endpoint,
+ router: UsersWeb.Router,
+ statics: UsersWeb.static_paths()
+ end
+ end
+
+ @doc """
+ When used, dispatch to the appropriate controller/live_view/etc.
+ """
+ defmacro __using__(which) when is_atom(which) do
+ apply(__MODULE__, which, [])
+ end
+end
diff --git a/users/lib/users_web/controllers/changeset_json.ex b/users/lib/users_web/controllers/changeset_json.ex
@@ -0,0 +1,12 @@
+defmodule UsersWeb.ChangesetJSON do
+ @doc "Renders changeset errors as `%{errors: %{field => [message]}}`."
+ def error(%{changeset: changeset}) do
+ %{errors: Ecto.Changeset.traverse_errors(changeset, &translate_error/1)}
+ end
+
+ defp translate_error({msg, opts}) do
+ Regex.replace(~r"%{(\w+)}", msg, fn _, key ->
+ opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
+ end)
+ end
+end
diff --git a/users/lib/users_web/controllers/error_json.ex b/users/lib/users_web/controllers/error_json.ex
@@ -0,0 +1,24 @@
+defmodule UsersWeb.ErrorJSON do
+ @moduledoc """
+ This module is invoked by your endpoint in case of errors on JSON requests.
+
+ See config/config.exs.
+ """
+
+ # If you want to customize a particular status code,
+ # you may add your own clauses, such as:
+ #
+ # def render("500.json", _assigns) do
+ # %{errors: %{detail: "Internal Server Error"}}
+ # end
+
+ @doc "Renders an error with a custom message."
+ def detail(%{detail: detail}), do: %{errors: %{detail: detail}}
+
+ # By default, Phoenix returns the status message from
+ # the template name. For example, "404.json" becomes
+ # "Not Found".
+ def render(template, _assigns) do
+ %{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
+ end
+end
diff --git a/users/lib/users_web/controllers/fallback_controller.ex b/users/lib/users_web/controllers/fallback_controller.ex
@@ -0,0 +1,35 @@
+defmodule UsersWeb.FallbackController do
+ @moduledoc "Turns the error tuples returned by controller actions into responses."
+ use UsersWeb, :controller
+
+ def call(conn, {:error, %Ecto.Changeset{} = changeset}) do
+ status = if name_taken?(changeset), do: :conflict, else: :unprocessable_entity
+
+ conn
+ |> put_status(status)
+ |> put_view(json: UsersWeb.ChangesetJSON)
+ |> render(:error, changeset: changeset)
+ end
+
+ def call(conn, {:error, :bad_request}),
+ do: detail(conn, :bad_request, "name and password are required")
+
+ def call(conn, {:error, :auth_rejected}),
+ do: detail(conn, :bad_gateway, "auth service rejected the credentials")
+
+ def call(conn, {:error, :auth_unavailable}),
+ do: detail(conn, :service_unavailable, "auth service unavailable")
+
+ defp detail(conn, status, message) do
+ conn
+ |> put_status(status)
+ |> put_view(json: UsersWeb.ErrorJSON)
+ |> render(:detail, detail: message)
+ end
+
+ defp name_taken?(changeset) do
+ Enum.any?(changeset.errors, fn {field, {_msg, opts}} ->
+ field == :name and opts[:constraint] == :unique
+ end)
+ end
+end
diff --git a/users/lib/users_web/controllers/session_controller.ex b/users/lib/users_web/controllers/session_controller.ex
@@ -0,0 +1,25 @@
+defmodule UsersWeb.SessionController do
+ use UsersWeb, :controller
+
+ alias Users.Accounts
+
+ action_fallback UsersWeb.FallbackController
+
+ @doc "Logs in through the auth service and relays its answer unchanged."
+ def create(conn, %{"name" => name, "password" => password})
+ when is_binary(name) and is_binary(password) do
+ with {:ok, response} <- Accounts.login(name, password) do
+ content_type =
+ case Req.Response.get_header(response, "content-type") do
+ [value | _] -> value
+ [] -> "text/plain"
+ end
+
+ conn
+ |> put_resp_header("content-type", content_type)
+ |> send_resp(response.status, response.body)
+ end
+ end
+
+ def create(_conn, _params), do: {:error, :bad_request}
+end
diff --git a/users/lib/users_web/controllers/user_controller.ex b/users/lib/users_web/controllers/user_controller.ex
@@ -0,0 +1,17 @@
+defmodule UsersWeb.UserController do
+ use UsersWeb, :controller
+
+ alias Users.Accounts
+
+ action_fallback UsersWeb.FallbackController
+
+ def create(conn, params) do
+ attrs = Map.take(params, ["name", "password"])
+
+ with {:ok, user} <- Accounts.create_user(attrs) do
+ conn
+ |> put_status(:created)
+ |> render(:show, user: user)
+ end
+ end
+end
diff --git a/users/lib/users_web/controllers/user_json.ex b/users/lib/users_web/controllers/user_json.ex
@@ -0,0 +1,7 @@
+defmodule UsersWeb.UserJSON do
+ alias Users.Accounts.User
+
+ def show(%{user: user}), do: data(user)
+
+ defp data(%User{} = user), do: %{name: user.name}
+end
diff --git a/users/lib/users_web/endpoint.ex b/users/lib/users_web/endpoint.ex
@@ -0,0 +1,49 @@
+defmodule UsersWeb.Endpoint do
+ use Phoenix.Endpoint, otp_app: :users
+
+ # The session will be stored in the cookie and signed,
+ # this means its contents can be read but not tampered with.
+ # Set :encryption_salt if you would also like to encrypt it.
+ @session_options [
+ store: :cookie,
+ key: "_users_key",
+ signing_salt: "zxmzAnTp",
+ same_site: "Lax"
+ ]
+
+ # socket "/live", Phoenix.LiveView.Socket,
+ # websocket: [connect_info: [session: @session_options]],
+ # longpoll: [connect_info: [session: @session_options]]
+
+ # Serve at "/" the static files from "priv/static" directory.
+ #
+ # When code reloading is disabled (e.g., in production),
+ # the `gzip` option is enabled to serve compressed
+ # static files generated by running `phx.digest`.
+ plug Plug.Static,
+ at: "/",
+ from: :users,
+ gzip: not code_reloading?,
+ only: UsersWeb.static_paths(),
+ raise_on_missing_only: code_reloading?
+
+ # Code reloading can be explicitly enabled under the
+ # :code_reloader configuration of your endpoint.
+ if code_reloading? do
+ plug Phoenix.CodeReloader
+ plug Phoenix.Ecto.CheckRepoStatus, otp_app: :users
+ end
+
+ plug Plug.RequestId
+ plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
+
+ plug Plug.Parsers,
+ parsers: [:urlencoded, :multipart, :json],
+ pass: ["*/*"],
+ json_decoder: Phoenix.json_library()
+
+ plug Plug.MethodOverride
+ plug Plug.Head
+ plug Plug.Session, @session_options
+ plug UsersWeb.Router
+end
diff --git a/users/lib/users_web/router.ex b/users/lib/users_web/router.ex
@@ -0,0 +1,14 @@
+defmodule UsersWeb.Router do
+ use UsersWeb, :router
+
+ pipeline :api do
+ plug :accepts, ["json"]
+ end
+
+ scope "/", UsersWeb do
+ pipe_through :api
+
+ post "/users", UserController, :create
+ post "/login", SessionController, :create
+ end
+end
diff --git a/users/lib/users_web/telemetry.ex b/users/lib/users_web/telemetry.ex
@@ -0,0 +1,93 @@
+defmodule UsersWeb.Telemetry do
+ use Supervisor
+ import Telemetry.Metrics
+
+ def start_link(arg) do
+ Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
+ end
+
+ @impl true
+ def init(_arg) do
+ children = [
+ # Telemetry poller will execute the given period measurements
+ # every 10_000ms. Learn more here: https://telemetry-metrics.hexdocs.pm
+ {:telemetry_poller, measurements: periodic_measurements(), period: 10_000}
+ # Add reporters as children of your supervision tree.
+ # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
+ ]
+
+ Supervisor.init(children, strategy: :one_for_one)
+ end
+
+ def metrics do
+ [
+ # Phoenix Metrics
+ summary("phoenix.endpoint.start.system_time",
+ unit: {:native, :millisecond}
+ ),
+ summary("phoenix.endpoint.stop.duration",
+ unit: {:native, :millisecond}
+ ),
+ summary("phoenix.router_dispatch.start.system_time",
+ tags: [:route],
+ unit: {:native, :millisecond}
+ ),
+ summary("phoenix.router_dispatch.exception.duration",
+ tags: [:route],
+ unit: {:native, :millisecond}
+ ),
+ summary("phoenix.router_dispatch.stop.duration",
+ tags: [:route],
+ unit: {:native, :millisecond}
+ ),
+ summary("phoenix.socket_connected.duration",
+ unit: {:native, :millisecond}
+ ),
+ sum("phoenix.socket_drain.count"),
+ summary("phoenix.channel_joined.duration",
+ unit: {:native, :millisecond}
+ ),
+ summary("phoenix.channel_handled_in.duration",
+ tags: [:event],
+ unit: {:native, :millisecond}
+ ),
+
+ # Database Metrics
+ summary("users.repo.query.total_time",
+ unit: {:native, :millisecond},
+ description: "The sum of the other measurements"
+ ),
+ summary("users.repo.query.decode_time",
+ unit: {:native, :millisecond},
+ description: "The time spent decoding the data received from the database"
+ ),
+ summary("users.repo.query.query_time",
+ unit: {:native, :millisecond},
+ description: "The time spent executing the query"
+ ),
+ summary("users.repo.query.queue_time",
+ unit: {:native, :millisecond},
+ description: "The time spent waiting for a database connection"
+ ),
+ summary("users.repo.query.idle_time",
+ unit: {:native, :millisecond},
+ description:
+ "The time the connection spent waiting before being checked out for the query"
+ ),
+
+ # VM Metrics
+ summary("vm.memory.total", unit: {:byte, :kilobyte}),
+ summary("vm.total_run_queue_lengths.total"),
+ summary("vm.total_run_queue_lengths.cpu"),
+ summary("vm.total_run_queue_lengths.io")
+ ]
+ end
+
+ defp periodic_measurements do
+ [
+ # A module, function and arguments to be invoked periodically.
+ # This function must call :telemetry.execute/3 and a metric must be added above.
+ # {UsersWeb, :count_users, []}
+ ]
+ end
+end
diff --git a/users/mix.exs b/users/mix.exs
@@ -0,0 +1,70 @@
+defmodule Users.MixProject do
+ use Mix.Project
+
+ def project do
+ [
+ app: :users,
+ version: "0.1.0",
+ elixir: "~> 1.17",
+ elixirc_paths: elixirc_paths(Mix.env()),
+ start_permanent: Mix.env() == :prod,
+ aliases: aliases(),
+ deps: deps(),
+ listeners: [Phoenix.CodeReloader]
+ ]
+ end
+
+ # Configuration for the OTP application.
+ #
+ # Type `mix help compile.app` for more information.
+ def application do
+ [
+ mod: {Users.Application, []},
+ extra_applications: [:logger, :runtime_tools]
+ ]
+ end
+
+ def cli do
+ [
+ preferred_envs: [precommit: :test]
+ ]
+ end
+
+ # Specifies which paths to compile per environment.
+ defp elixirc_paths(:test), do: ["lib", "test/support"]
+ defp elixirc_paths(_), do: ["lib"]
+
+ # Specifies your project dependencies.
+ #
+ # Type `mix help deps` for examples and options.
+ defp deps do
+ [
+ {:phoenix, "~> 1.8.16"},
+ {:phoenix_ecto, "~> 4.5"},
+ {:ecto_sql, "~> 3.13"},
+ {:ecto_sqlite3, ">= 0.0.0"},
+ {:telemetry_metrics, "~> 1.0"},
+ {:telemetry_poller, "~> 1.0"},
+ {:jason, "~> 1.2"},
+ {:dns_cluster, "~> 0.2.0"},
+ {:bandit, "~> 1.5"},
+ {:req, "~> 0.5"}
+ ]
+ end
+
+ # Aliases are shortcuts or tasks specific to the current project.
+ # For example, to install project dependencies and perform other setup tasks, run:
+ #
+ # $ mix setup
+ #
+ # See the documentation for `Mix` for more info on aliases.
+ defp aliases do
+ [
+ setup: ["deps.get", "ecto.setup"],
+ "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
+ "ecto.reset": ["ecto.drop", "ecto.setup"],
+ test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"],
+ precommit: ["compile --warnings-as-errors", "deps.unlock --unused", "format", "test"]
+ ]
+ end
+end
diff --git a/users/mix.lock b/users/mix.lock
@@ -0,0 +1,32 @@
+%{
+ "bandit": {:hex, :bandit, "1.15.0", "df5991a93535e83f9e939bee4af539e0ce17269a0d42fc63819daae60c7d23df", [:mix], [{:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}, {:plug, "~> 1.18", [hex: :plug, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:thousand_island, "~> 1.6", [hex: :thousand_island, repo: "hexpm", optional: false]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "e3b29c4a5107f4bf7dfaa263c50b9b97ddcc132622197c110e2e10a921641c44"},
+ "cc_precompiler": {:hex, :cc_precompiler, "0.1.11", "8c844d0b9fb98a3edea067f94f616b3f6b29b959b6b3bf25fee94ffe34364768", [:mix], [{:elixir_make, "~> 0.7", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "3427232caf0835f94680e5bcf082408a70b48ad68a5f5c0b02a3bea9f3a075b9"},
+ "db_connection": {:hex, :db_connection, "2.10.2", "ae391e803a5adff104da913c2fc1c0c14a37f8b10001dcef568796e1fb7bf95c", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "510b14482330f1af6490a2fa0efd8d4f1435d1529b165647df22ac0f2df0fa93"},
+ "decimal": {:hex, :decimal, "3.2.0", "f1235f05d841a211fda78a08fdb9777f2ff51a71f18455233fae186ff76187c6", [:mix], [], "hexpm", "190bca80580ce61aa69bb0eacadd7677710205c770225c2c2c07e32a5c31b234"},
+ "dns_cluster": {:hex, :dns_cluster, "0.2.0", "aa8eb46e3bd0326bd67b84790c561733b25c5ba2fe3c7e36f28e88f384ebcb33", [:mix], [], "hexpm", "ba6f1893411c69c01b9e8e8f772062535a4cf70f3f35bcc964a324078d8c8240"},
+ "ecto": {:hex, :ecto, "3.14.3", "4e7f7728c1432b18d8a48e4aeef879e8b908ecefd66afde17adb8cca0a46eff4", [:mix], [{:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "da2548bd3ced0f56c27d54255389bbbb8f110150ce15cffc95ec0cafa364465c"},
+ "ecto_sql": {:hex, :ecto_sql, "3.14.0", "06446ab8410d2f85bfbb80857ee224ab3b693700cbb38f6535d507449a627b2e", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:ecto, "~> 3.14.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:myxql, "~> 0.8", [hex: :myxql, repo: "hexpm", optional: true]}, {:postgrex, "~> 0.19 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}, {:tds, "~> 2.1.1 or ~> 2.2", [hex: :tds, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.0 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "f4d8d36faf294c9417b5a37ec7ac8217ee2abdef5fcf197ba690f361548d3949"},
+ "ecto_sqlite3": {:hex, :ecto_sqlite3, "0.26.0", "abe7f5aeefc40dfa2c300d1c1954534e7a8dcd6125312795593efb3c2e5ff44e", [:mix], [{:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:ecto, "~> 3.14", [hex: :ecto, repo: "hexpm", optional: false]}, {:ecto_sql, "~> 3.14", [hex: :ecto_sql, repo: "hexpm", optional: false]}, {:exqlite, "~> 0.40", [hex: :exqlite, repo: "hexpm", optional: false]}], "hexpm", "e04d69e185f27a604dd116144a1bad36595666546d753e9341a3f3736ee64772"},
+ "elixir_make": {:hex, :elixir_make, "0.10.1", "f5a44ab6b48421de1c4fd33c147e22cd2f82fd86e8a9a4d24809d466cad63c5e", [:mix], [], "hexpm", "ce1eaa234bc87f0279718e793fd6f8ad35b4e8ee8d412329e3879eee8d40adba"},
+ "exqlite": {:hex, :exqlite, "0.43.0", "ba1d5f83d5694a6c347661bf1176e06ce4b581f5d240bbaa41c32c2ec226b7c6", [:make, :mix], [{:cc_precompiler, "~> 0.1", [hex: :cc_precompiler, repo: "hexpm", optional: false]}, {:db_connection, "~> 2.1", [hex: :db_connection, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.8", [hex: :elixir_make, repo: "hexpm", optional: false]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "aa9996f5f582b01f641076632a03bfe139655606b2ba2c86bf528656adf22a5a"},
+ "finch": {:hex, :finch, "0.25.0", "ce6203ff9464baf7d82e71b9568cf061ed640317e7e3449dac7601d220689d53", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.2.0", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "9fd9a2c47a9033f4d70fad6e7d656948c08bc6652699de20e609a5917c0bb0a5"},
+ "hpax": {:hex, :hpax, "1.1.0", "782931867cc23217c68fb5f68fe1a11f5e7544c7fda82c8a7019a5df5a4a1cdf", [:mix], [], "hexpm", "0b8d0f05832f55571d65ac720f79bf8994138ffbb133209dc4685eae0ad456a8"},
+ "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"},
+ "mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
+ "mint": {:hex, :mint, "1.11.0", "a713551624815c0435237b93d90ea8b9b14254690c66f732d0ef8930f76ff1d9", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 1.1", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "c6279ba2d6aa3a383a1d4cfbe7b59f42e6efd400f58d8e2acfeac48a438693ab"},
+ "nimble_options": {:hex, :nimble_options, "1.2.0", "73e5c5fecb08e59f390e0f59c2320b585d72470dbdd9230a469e06881b9dd4a8", [:mix], [], "hexpm", "3a784a75ef9e407619c8c9e98239b1acd29216deb737044a8c1063e2671ce6d9"},
+ "nimble_pool": {:hex, :nimble_pool, "1.2.0", "7f7e19c4fc7e960ffd405b0bcaec73e29a96e249a806b386f57e18192f24fa4f", [:mix], [], "hexpm", "bc442e72578c21842589fa8e5886b6175fa5245fdbbad35fc08db277ac2b2c0d"},
+ "phoenix": {:hex, :phoenix, "1.8.16", "6a4742054740496bfabefc95253f978d8f595f07bb601039b7a18b384a873916", [:mix], [{:bandit, "~> 1.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:phoenix_pubsub, "~> 2.4", [hex: :phoenix_pubsub, repo: "hexpm", optional: false]}, {:phoenix_template, "~> 1.0", [hex: :phoenix_template, repo: "hexpm", optional: false]}, {:phoenix_view, "~> 2.0", [hex: :phoenix_view, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.7", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:plug_crypto, "~> 2.2", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:websock_adapter, "~> 0.5", [hex: :websock_adapter, repo: "hexpm", optional: false]}], "hexpm", "e7355c35889305bc539eb09dae2393abcbaf0f65f6874a3f0dcb5f0ec53737fe"},
+ "phoenix_ecto": {:hex, :phoenix_ecto, "4.7.0", "75c4b9dfb3efdc42aec2bd5f8bccd978aca0651dbcbc7a3f362ea5d9d43153c6", [:mix], [{:ecto, "~> 3.5", [hex: :ecto, repo: "hexpm", optional: false]}, {:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.1", [hex: :phoenix_html, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: false]}, {:postgrex, "~> 0.16 or ~> 1.0", [hex: :postgrex, repo: "hexpm", optional: true]}], "hexpm", "1d75011e4254cb4ddf823e81823a9629559a1be93b4321a6a5f11a5306fbf4cc"},
+ "phoenix_pubsub": {:hex, :phoenix_pubsub, "2.4.1", "2ff3e7ba8b432120989870997b9adaefb76e1f63805554ab0b9e948987981f4b", [:mix], [], "hexpm", "352fba7a87bf61395b6e97da66944ad9b1bfe5459e5981039f60d68270bd9700"},
+ "phoenix_template": {:hex, :phoenix_template, "1.1.0", "b329582281b1e00e4dc664afd60ef5b489cbb356923caa3b1e00abe8651b9a18", [:mix], [{:phoenix_html, "~> 2.14.2 or ~> 3.0 or ~> 4.0", [hex: :phoenix_html, repo: "hexpm", optional: true]}], "hexpm", "eba70070de79b2c3501ef205a74a69f98ab352f3785aa15da9ed161f9fe0fd5d"},
+ "plug": {:hex, :plug, "1.20.4", "8fca521b31eb586dbb91968dd9fa95be6b60fb40f9ca77b005361e06836aed75", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "96ee42c0b8b35bcb14e3e65afb85abe9bb7745a8576e8c602802bbb01e5acf72"},
+ "plug_crypto": {:hex, :plug_crypto, "2.2.1", "bd1d0358a2e2f5ffb818217e64c394f9d24ed191d862b7fa1bcce264ace2b8ea", [:mix], [], "hexpm", "4417ccbd8f85e627321cd07d2ab9c4b621f1fd883b9905af241f9b4b780b94b6"},
+ "req": {:hex, :req, "0.7.5", "0c3293cbf7717aba20b1b1b3ea13fe8d3fdf6f1557490f390c3f1ef6dd9db955", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "576853c4bf403faa3c1fa5d093e0759227083b78f8a6864c67d62c0a9c45514d"},
+ "telemetry": {:hex, :telemetry, "1.4.3", "d0333fa869361e6833d6ff8e806ff4d8553fe1332fcce0af86c7381951a1dc2f", [:rebar3], [], "hexpm", "17a63581cf2e832a238287f5fe6811e8ca1f333249f1376ad653164a3c4770d4"},
+ "telemetry_metrics": {:hex, :telemetry_metrics, "1.2.0", "7632c19c01d88d8aaca5da1a0e8912f5af39b79e7c08a2c253aeb3c14c2c957e", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "71dde12fc29b58b9c77ec17ec319109e5ca848d010fc1965ed4463bba1837c07"},
+ "telemetry_poller": {:hex, :telemetry_poller, "1.3.0", "d5c46420126b5ac2d72bc6580fb4f537d35e851cc0f8dbd571acf6d6e10f5ec7", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "51f18bed7128544a50f75897db9974436ea9bfba560420b646af27a9a9b35211"},
+ "thousand_island": {:hex, :thousand_island, "1.6.0", "d6ad7c2220c96a270cc8ca1586ec4d8bde648a4a3a53f003ce093f41beec0288", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4d4720470f091fc21a1311777c2ac66916c43621bffc068590c9f9bb3cd057a3"},
+ "websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"},
+ "websock_adapter": {:hex, :websock_adapter, "0.7.2", "2a70852d206daa9e75669030e9be9622f8919ff1e558665b9844413f4f9b4d84", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:roadrunner_plug, ">= 0.1.0", [hex: :roadrunner_plug, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "f9e80710008783864177c81e9d8418d05769ce10a26e9e538f5ed72e283f7358"},
+}
diff --git a/users/priv/repo/migrations/.formatter.exs b/users/priv/repo/migrations/.formatter.exs
@@ -0,0 +1,4 @@
+[
+ import_deps: [:ecto_sql],
+ inputs: ["*.exs"]
+]
diff --git a/users/priv/repo/migrations/20261119175430_create_users.exs b/users/priv/repo/migrations/20261119175430_create_users.exs
@@ -0,0 +1,10 @@
+defmodule Users.Repo.Migrations.CreateUsers do
+ use Ecto.Migration
+
+ def change do
+ # Only the list of names lives here; passwords are kept by the auth service.
+ create table(:users, primary_key: false) do
+ add :name, :string, primary_key: true
+ end
+ end
+end
diff --git a/users/priv/repo/seeds.exs b/users/priv/repo/seeds.exs
@@ -0,0 +1,11 @@
+# Script for populating the database. You can run it as:
+#
+# mix run priv/repo/seeds.exs
+#
+# Inside the script, you can read and write to any of your
+# repositories directly:
+#
+# Users.Repo.insert!(%Users.SomeSchema{})
+#
+# We recommend using the bang functions (`insert!`, `update!`
+# and so on) as they will fail if something goes wrong.
diff --git a/users/priv/static/favicon.ico b/users/priv/static/favicon.ico
Binary files differ.
diff --git a/users/priv/static/robots.txt b/users/priv/static/robots.txt
@@ -0,0 +1,5 @@
+# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
+#
+# To ban all spiders from the entire site uncomment the next two lines:
+# User-agent: *
+# Disallow: /
diff --git a/users/test/support/conn_case.ex b/users/test/support/conn_case.ex
@@ -0,0 +1,38 @@
+defmodule UsersWeb.ConnCase do
+ @moduledoc """
+ This module defines the test case to be used by
+ tests that require setting up a connection.
+
+ Such tests rely on `Phoenix.ConnTest` and also
+ import other functionality to make it easier
+ to build common data structures and query the data layer.
+
+ Finally, if the test case interacts with the database,
+ we enable the SQL sandbox, so changes done to the database
+ are reverted at the end of every test. If you are using
+ PostgreSQL, you can even run database tests asynchronously
+ by setting `use UsersWeb.ConnCase, async: true`, although
+ this option is not recommended for other databases.
+ """
+
+ use ExUnit.CaseTemplate
+
+ using do
+ quote do
+ # The default endpoint for testing
+ @endpoint UsersWeb.Endpoint
+
+ use UsersWeb, :verified_routes
+
+ # Import conveniences for testing with connections
+ import Plug.Conn
+ import Phoenix.ConnTest
+ import UsersWeb.ConnCase
+ end
+ end
+
+ setup tags do
+ Users.DataCase.setup_sandbox(tags)
+ {:ok, conn: Phoenix.ConnTest.build_conn()}
+ end
+end
diff --git a/users/test/support/data_case.ex b/users/test/support/data_case.ex
@@ -0,0 +1,58 @@
+defmodule Users.DataCase do
+ @moduledoc """
+ This module defines the setup for tests requiring
+ access to the application's data layer.
+
+ You may define functions here to be used as helpers in
+ your tests.
+
+ Finally, if the test case interacts with the database,
+ we enable the SQL sandbox, so changes done to the database
+ are reverted at the end of every test. If you are using
+ PostgreSQL, you can even run database tests asynchronously
+ by setting `use Users.DataCase, async: true`, although
+ this option is not recommended for other databases.
+ """
+
+ use ExUnit.CaseTemplate
+
+ using do
+ quote do
+ alias Users.Repo
+
+ import Ecto
+ import Ecto.Changeset
+ import Ecto.Query
+ import Users.DataCase
+ end
+ end
+
+ setup tags do
+ Users.DataCase.setup_sandbox(tags)
+ :ok
+ end
+
+ @doc """
+ Sets up the sandbox based on the test tags.
+ """
+ def setup_sandbox(tags) do
+ pid = Ecto.Adapters.SQL.Sandbox.start_owner!(Users.Repo, shared: not tags[:async])
+ on_exit(fn -> Ecto.Adapters.SQL.Sandbox.stop_owner(pid) end)
+ end
+
+ @doc """
+ A helper that transforms changeset errors into a map of messages.
+
+ assert {:error, changeset} = Accounts.create_user(%{password: "short"})
+ assert "password is too short" in errors_on(changeset).password
+ assert %{password: ["password is too short"]} = errors_on(changeset)
+
+ """
+ def errors_on(changeset) do
+ Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
+ Regex.replace(~r"%{(\w+)}", message, fn _, key ->
+ opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
+ end)
+ end)
+ end
+end
diff --git a/users/test/test_helper.exs b/users/test/test_helper.exs
@@ -0,0 +1,2 @@
+ExUnit.start()
+Ecto.Adapters.SQL.Sandbox.mode(Users.Repo, :manual)
diff --git a/users/test/users/accounts_test.exs b/users/test/users/accounts_test.exs
@@ -0,0 +1,64 @@
+defmodule Users.AccountsTest do
+ use Users.DataCase, async: true
+ @moduletag :capture_log
+
+ alias Users.Accounts
+ alias Users.Accounts.User
+ alias Users.Repo
+
+ defp stub_auth(status) do
+ Req.Test.stub(Users.Auth, fn conn ->
+ {:ok, body, conn} = Plug.Conn.read_body(conn)
+ send(self(), {:auth_request, conn.method, conn.request_path, Jason.decode!(body)})
+ Plug.Conn.send_resp(conn, status, "")
+ end)
+ end
+
+ describe "create_user/1" do
+ test "stores only the name and sends the credentials to auth" do
+ stub_auth(200)
+
+ assert {:ok, %User{name: "ana", password: nil}} =
+ Accounts.create_user(%{"name" => "ana", "password" => "segredo"})
+
+ assert_received {:auth_request, "POST", "/credentials",
+ %{"Username" => "ana", "Password" => "segredo"}}
+
+ assert [%User{name: "ana"}] = Repo.all(User)
+ end
+
+ test "requires name and password, without calling auth" do
+ assert {:error, changeset} = Accounts.create_user(%{"name" => "", "password" => nil})
+ assert %{name: ["can't be blank"], password: ["can't be blank"]} = errors_on(changeset)
+ refute_received {:auth_request, _, _, _}
+ end
+
+ test "rejects a name that is already taken, without calling auth" do
+ stub_auth(200)
+ {:ok, _} = Accounts.create_user(%{"name" => "ana", "password" => "a"})
+ assert_received {:auth_request, _, _, _}
+
+ assert {:error, changeset} = Accounts.create_user(%{"name" => "ana", "password" => "b"})
+ assert %{name: ["has already been taken"]} = errors_on(changeset)
+ refute_received {:auth_request, _, _, _}
+ end
+
+ test "rolls back the name when auth rejects the credentials" do
+ stub_auth(500)
+
+ assert {:error, :auth_rejected} =
+ Accounts.create_user(%{"name" => "ana", "password" => "a"})
+
+ assert Repo.all(User) == []
+ end
+
+ test "rolls back the name when auth is unreachable" do
+ Req.Test.stub(Users.Auth, &Req.Test.transport_error(&1, :econnrefused))
+
+ assert {:error, :auth_unavailable} =
+ Accounts.create_user(%{"name" => "ana", "password" => "a"})
+
+ assert Repo.all(User) == []
+ end
+ end
+end
diff --git a/users/test/users_web/controllers/error_json_test.exs b/users/test/users_web/controllers/error_json_test.exs
@@ -0,0 +1,12 @@
+defmodule UsersWeb.ErrorJSONTest do
+ use UsersWeb.ConnCase, async: true
+
+ test "renders 404" do
+ assert UsersWeb.ErrorJSON.render("404.json", %{}) == %{errors: %{detail: "Not Found"}}
+ end
+
+ test "renders 500" do
+ assert UsersWeb.ErrorJSON.render("500.json", %{}) ==
+ %{errors: %{detail: "Internal Server Error"}}
+ end
+end
diff --git a/users/test/users_web/controllers/session_controller_test.exs b/users/test/users_web/controllers/session_controller_test.exs
@@ -0,0 +1,42 @@
+defmodule UsersWeb.SessionControllerTest do
+ use UsersWeb.ConnCase, async: true
+ @moduletag :capture_log
+
+ test "POST /login relays a successful login", %{conn: conn} do
+ Req.Test.stub(Users.Auth, fn auth_conn ->
+ {:ok, body, auth_conn} = Plug.Conn.read_body(auth_conn)
+ assert auth_conn.request_path == "/login"
+ assert Jason.decode!(body) == %{"Username" => "ana", "Password" => "segredo"}
+ Req.Test.json(auth_conn, %{"Token" => "8b47881d-650f-4ab1-a38a-bbf3e19ac0d2"})
+ end)
+
+ conn = post(conn, ~p"/login", %{name: "ana", password: "segredo"})
+ assert json_response(conn, 200) == %{"Token" => "8b47881d-650f-4ab1-a38a-bbf3e19ac0d2"}
+ end
+
+ test "POST /login relays a failed login unchanged", %{conn: conn} do
+ Req.Test.stub(Users.Auth, fn auth_conn ->
+ auth_conn
+ |> Plug.Conn.put_resp_content_type("text/plain")
+ |> Plug.Conn.send_resp(401, "invalid username or password\n")
+ end)
+
+ conn = post(conn, ~p"/login", %{name: "ana", password: "errada"})
+ assert response(conn, 401) == "invalid username or password\n"
+ assert response_content_type(conn, :text)
+ end
+
+ test "POST /login without credentials answers 400", %{conn: conn} do
+ conn = post(conn, ~p"/login", %{name: "ana"})
+
+ assert json_response(conn, 400) == %{
+ "errors" => %{"detail" => "name and password are required"}
+ }
+ end
+
+ test "POST /login answers 503 when auth is down", %{conn: conn} do
+ Req.Test.stub(Users.Auth, &Req.Test.transport_error(&1, :econnrefused))
+ conn = post(conn, ~p"/login", %{name: "ana", password: "a"})
+ assert json_response(conn, 503)
+ end
+end
diff --git a/users/test/users_web/controllers/user_controller_test.exs b/users/test/users_web/controllers/user_controller_test.exs
@@ -0,0 +1,37 @@
+defmodule UsersWeb.UserControllerTest do
+ use UsersWeb.ConnCase, async: true
+ @moduletag :capture_log
+
+ setup do
+ Req.Test.stub(Users.Auth, &Plug.Conn.send_resp(&1, 200, ""))
+ :ok
+ end
+
+ test "POST /users creates a user", %{conn: conn} do
+ conn = post(conn, ~p"/users", %{name: "ana", password: "segredo"})
+ assert json_response(conn, 201) == %{"name" => "ana"}
+ end
+
+ test "POST /users with a taken name answers 409", %{conn: conn} do
+ post(conn, ~p"/users", %{name: "ana", password: "a"})
+ conn = post(conn, ~p"/users", %{name: "ana", password: "b"})
+ assert json_response(conn, 409) == %{"errors" => %{"name" => ["has already been taken"]}}
+ end
+
+ test "POST /users with missing fields answers 422", %{conn: conn} do
+ conn = post(conn, ~p"/users", %{name: "ana"})
+ assert json_response(conn, 422) == %{"errors" => %{"password" => ["can't be blank"]}}
+ end
+
+ test "POST /users answers 503 when auth is down", %{conn: conn} do
+ Req.Test.stub(Users.Auth, &Req.Test.transport_error(&1, :econnrefused))
+ conn = post(conn, ~p"/users", %{name: "ana", password: "a"})
+ assert json_response(conn, 503) == %{"errors" => %{"detail" => "auth service unavailable"}}
+ end
+
+ test "POST /users answers 502 when auth rejects the credentials", %{conn: conn} do
+ Req.Test.stub(Users.Auth, &Plug.Conn.send_resp(&1, 500, "internal server error"))
+ conn = post(conn, ~p"/users", %{name: "ana", password: "a"})
+ assert json_response(conn, 502)
+ end
+end