Create schemas for JSON API endpoints

This commit is contained in:
Pim Kunis 2021-06-26 22:02:18 +02:00
parent 1ec18163c1
commit 7c73c2c424
11 changed files with 125 additions and 105 deletions

View file

@ -37,4 +37,18 @@ defmodule MatrixServer do
def server_name do def server_name do
Application.get_env(:matrix_server, :server_name) Application.get_env(:matrix_server, :server_name)
end end
def update_map_entry(map, old_key, new_key) do
update_map_entry(map, old_key, new_key, &Function.identity/1)
end
def update_map_entry(map, old_key, new_key, fun) when is_map_key(map, old_key) do
value = Map.fetch!(map, old_key)
map
|> Map.put(new_key, fun.(value))
|> Map.delete(old_key)
end
def update_map_entry(map, _, _, _), do: map
end end

View file

@ -34,11 +34,14 @@ defmodule MatrixServer.Account do
end end
end end
def register(params) do def register(account, params) do
Multi.new() Multi.new()
|> Multi.insert(:account, changeset(%Account{}, params)) |> Multi.insert(:account, changeset(account, params))
|> Multi.insert(:device, fn %{account: account} -> |> Multi.insert(:device, fn %{account: account} ->
device_id = Device.generate_device_id(account)
Ecto.build_assoc(account, :devices) Ecto.build_assoc(account, :devices)
|> Map.put(:device_id, device_id)
|> Device.changeset(params) |> Device.changeset(params)
end) end)
|> Multi.run(:device_with_access_token, &Device.generate_access_token/2) |> Multi.run(:device_with_access_token, &Device.generate_access_token/2)

View file

@ -33,4 +33,13 @@ defmodule MatrixServer.Device do
|> change(%{access_token: access_token}) |> change(%{access_token: access_token})
|> repo.update() |> repo.update()
end end
def generate_device_id(%Account{localpart: localpart}) do
time_string =
DateTime.utc_now()
|> DateTime.to_unix()
|> Integer.to_string()
"#{localpart}_#{time_string}"
end
end end

View file

@ -0,0 +1,38 @@
defmodule MatrixServerWeb.API.Register do
use Ecto.Schema
import Ecto.Changeset
import MatrixServerWeb.Plug.Error
alias __MODULE__
alias Ecto.Changeset
embedded_schema do
field :device_id, :string
field :initial_device_display_name, :string
field :password, :string
field :username, :string
field :inhibit_login, :boolean, default: false
end
def changeset(params) do
%Register{}
|> cast(params, [
:device_id,
:initial_device_display_name,
:password,
:username,
:inhibit_login
])
|> validate_required([:password, :username])
end
def handle_error(conn, cs) do
put_error(conn, get_register_error(cs))
end
defp get_register_error(%Changeset{errors: [error | _]}), do: get_register_error(error)
defp get_register_error({:localpart, {_, [{:constraint, :unique} | _]}}), do: :user_in_use
defp get_register_error({:localpart, {_, [{:validation, _} | _]}}), do: :invalid_username
defp get_register_error(_), do: :bad_json
end

View file

@ -3,48 +3,49 @@ defmodule MatrixServerWeb.AuthController do
import MatrixServer import MatrixServer
import MatrixServerWeb.Plug.Error import MatrixServerWeb.Plug.Error
import Ecto.Changeset, only: [apply_changes: 1]
alias MatrixServer.{Repo, Account} alias MatrixServer.{Repo, Account}
alias MatrixServerWeb.API.Register
alias Ecto.Changeset alias Ecto.Changeset
@login_type "m.login.dummy" @register_type "m.login.dummy"
@login_type "m.login.password"
def register(conn, %{"auth" => %{"type" => @login_type}} = params) do def register(conn, %{"auth" => %{"type" => @register_type}} = params) do
# User has started an auth flow. case Register.changeset(params) do
result = %Changeset{valid?: true} = cs ->
case sanitize_register_params(params) do input =
{:ok, params} -> apply_changes(cs)
case Repo.transaction(Account.register(params)) do |> Map.from_struct()
{:ok, changeset} -> {:ok, changeset} |> update_map_entry(:initial_device_display_name, :device_name)
{:error, _, changeset, _} -> {:error, get_register_error(changeset)} |> update_map_entry(:username, :localpart)
end |> update_map_entry(:password, :password_hash, &Bcrypt.hash_pwd_salt/1)
{:error, changeset} -> case Account.register(%Account{}, input) |> Repo.transaction() do
{:error, get_register_error(changeset)}
end
{status, data} =
case result do
{:ok, %{device_with_access_token: device}} -> {:ok, %{device_with_access_token: device}} ->
data = %{user_id: get_mxid(device.localpart)} data = %{user_id: get_mxid(device.localpart)}
data = data =
if Map.get(params, "inhibit_login", false) == false do if not input.inhibit_login do
extra = %{device_id: device.device_id, access_token: device.access_token} data
Map.merge(data, extra) |> Map.put(:device_id, device.device_id)
|> Map.put(:access_token, device.access_token)
else else
data data
end end
{200, data} conn
|> put_status(200)
|> json(data)
{:error, error} -> {:error, _, cs, _} ->
put_error(conn, error) Register.handle_error(conn, cs)
end end
conn _ ->
|> put_status(status) put_error(conn, :bad_json)
|> json(data) end
end end
def register(conn, %{"auth" => _}) do def register(conn, %{"auth" => _}) do
@ -55,7 +56,7 @@ defmodule MatrixServerWeb.AuthController do
def register(conn, _params) do def register(conn, _params) do
# User has not started an auth flow. # User has not started an auth flow.
data = %{ data = %{
flows: [%{stages: [@login_type]}], flows: [%{stages: [@register_type]}],
params: %{} params: %{}
} }
@ -64,46 +65,22 @@ defmodule MatrixServerWeb.AuthController do
|> json(data) |> json(data)
end end
defp sanitize_register_params(params) do def login_types(conn, _params) do
changeset =
validate_api_schema(params, register_schema())
|> convert_change(:username, :localpart)
|> convert_change(:password, :password_hash, &Bcrypt.hash_pwd_salt/1)
case changeset do
%Changeset{valid?: true, changes: changes} -> {:ok, changes}
_ -> {:error, changeset}
end
end
defp get_register_error(%Changeset{errors: [error | _]}), do: get_register_error(error)
defp get_register_error({:localpart, {_, [{:constraint, :unique} | _]}}), do: :user_in_use
defp get_register_error({:localpart, {_, [{:validation, _} | _]}}), do: :invalid_username
defp get_register_error(_), do: :bad_json
defp register_schema do
types = %{
device_id: :string,
initial_device_display_name: :string,
display_name: :string,
password: :string,
username: :string,
localpart: :string,
password_hash: :string,
access_token: :string
}
allowed = [:device_id, :initial_device_display_name, :username, :password]
required = [:username, :password]
{types, allowed, required}
end
def login(conn, _params) do
data = %{flows: [%{type: @login_type}]} data = %{flows: [%{type: @login_type}]}
conn conn
|> put_status(200) |> put_status(200)
|> json(data) |> json(data)
end end
def login(conn, %{"type" => "m.login.password"}) do
conn
|> put_status(200)
|> json(%{})
end
def login(conn, _params) do
# Login type m.login.token is unsupported for now.
put_error(conn, :forbidden)
end
end end

View file

@ -1,6 +1,8 @@
defmodule MatrixServerWeb.InfoController do defmodule MatrixServerWeb.InfoController do
use MatrixServerWeb, :controller use MatrixServerWeb, :controller
import MatrixServerWeb.Plug.Error
@supported_versions ["r0.6.1"] @supported_versions ["r0.6.1"]
def versions(conn, _params) do def versions(conn, _params) do
@ -10,4 +12,8 @@ defmodule MatrixServerWeb.InfoController do
|> put_status(200) |> put_status(200)
|> json(data) |> json(data)
end end
def unrecognized(conn, _params) do
put_error(conn, :unrecognized)
end
end end

View file

@ -1,7 +1,6 @@
defmodule MatrixServerWeb.Plug.Authenticate do defmodule MatrixServerWeb.Plug.Authenticate do
import MatrixServerWeb.Plug.Error import MatrixServerWeb.Plug.Error
import Plug.Conn import Plug.Conn
import Phoenix.Controller, only: [json: 2]
alias MatrixServer.Account alias MatrixServer.Account
alias Plug.Conn alias Plug.Conn

View file

@ -7,6 +7,7 @@ defmodule MatrixServerWeb.Plug.Error do
user_in_use: {400, "M_USE_IN_USE", "Username is already taken."}, user_in_use: {400, "M_USE_IN_USE", "Username is already taken."},
invalid_username: {400, "M_INVALID_USERNAME", "Invalid username."}, invalid_username: {400, "M_INVALID_USERNAME", "Invalid username."},
forbidden: {400, "M_FORBIDDEN", "The requested action is forbidden."}, forbidden: {400, "M_FORBIDDEN", "The requested action is forbidden."},
unrecognized: {400, "M_UNRECOGNIZED", "Unrecognized request."},
unknown_token: {401, "M_UNKNOWN_TOKEN", "Invalid access token."}, unknown_token: {401, "M_UNKNOWN_TOKEN", "Invalid access token."},
missing_token: {401, "M_MISSING_TOKEN", "Access token required."} missing_token: {401, "M_MISSING_TOKEN", "Access token required."}
} }

View file

@ -17,7 +17,8 @@ defmodule MatrixServerWeb.Router do
scope "/client/r0", as: :client do scope "/client/r0", as: :client do
post "/register", AuthController, :register post "/register", AuthController, :register
get "/login", AuthController, :login get "/login", AuthController, :login_types
post "/login", AuthController, :login
get "/register/available", AccountController, :available get "/register/available", AccountController, :available
end end
@ -31,4 +32,8 @@ defmodule MatrixServerWeb.Router do
get "/account/whoami", AccountController, :whoami get "/account/whoami", AccountController, :whoami
end end
end end
scope "/", MatrixServerWeb do
match :*, "/*path", InfoController, :unrecognized
end
end end

View file

@ -1,16 +0,0 @@
defmodule MatrixServerWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
@doc """
Translates an error message.
"""
def translate_error({msg, opts}) do
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
Enum.reduce(opts, msg, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end
end

View file

@ -1,16 +0,0 @@
defmodule MatrixServerWeb.ErrorView do
use MatrixServerWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def template_not_found(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end