accounts.ex (987B)
1 defmodule Users.Accounts do 2 @moduledoc """ 3 User accounts. Names are stored here; credentials live in the auth service. 4 """ 5 alias Users.Accounts.User 6 alias Users.Auth 7 alias Users.Repo 8 9 @doc """ 10 Creates a user and its credentials in the auth service. 11 12 The name is inserted inside a transaction that is rolled back if the auth 13 service does not accept the credentials, so both sides stay in sync. 14 """ 15 @spec create_user(map()) :: 16 {:ok, User.t()} 17 | {:error, Ecto.Changeset.t()} 18 | {:error, :auth_rejected | :auth_unavailable} 19 def create_user(attrs) do 20 changeset = User.registration_changeset(%User{}, attrs) 21 22 Repo.transact(fn -> 23 with {:ok, user} <- Repo.insert(changeset), 24 :ok <- Auth.create_credentials(user.name, user.password) do 25 {:ok, %{user | password: nil}} 26 end 27 end) 28 end 29 30 @doc "Logs a user in. Relays the auth service response as is." 31 defdelegate login(name, password), to: Auth 32 end