architex/lib/matrix_server_web/controllers/auth_controller.ex

104 lines
2.5 KiB
Elixir
Raw Normal View History

defmodule MatrixServerWeb.AuthController do
use MatrixServerWeb, :controller
2021-06-25 23:14:09 +00:00
import MatrixServerWeb.Plug.Error
2021-07-10 21:16:00 +00:00
import Ecto.Changeset
2021-07-10 21:16:00 +00:00
alias MatrixServer.{Repo, Account}
2021-06-27 15:28:28 +00:00
alias MatrixServerWeb.API.{Register, Login}
alias Ecto.Changeset
2021-06-26 20:02:18 +00:00
@register_type "m.login.dummy"
@login_type "m.login.password"
def register(conn, %{"auth" => %{"type" => @register_type}} = params) do
case Register.changeset(params) do
%Changeset{valid?: true} = cs ->
2021-07-17 15:38:20 +00:00
input = apply_changes(cs)
2021-06-26 20:02:18 +00:00
2021-07-17 15:38:20 +00:00
case Account.register(input) |> Repo.transaction() do
2021-06-26 20:02:18 +00:00
{:ok, %{device_with_access_token: device}} ->
2021-07-10 21:16:00 +00:00
data = %{user_id: MatrixServer.get_mxid(device.localpart)}
2021-06-26 20:02:18 +00:00
data =
2021-07-17 15:38:20 +00:00
if not input.inhibit_login do
2021-06-26 20:02:18 +00:00
data
|> Map.put(:device_id, device.device_id)
|> Map.put(:access_token, device.access_token)
else
data
end
conn
|> put_status(200)
|> json(data)
{:error, _, cs, _} ->
2021-07-10 21:16:00 +00:00
put_error(conn, Register.get_error(cs))
2021-06-26 20:02:18 +00:00
end
_ ->
put_error(conn, :bad_json)
end
end
def register(conn, %{"auth" => _}) do
# Other login types are unsupported for now.
2021-06-25 23:14:09 +00:00
put_error(conn, :forbidden)
end
def register(conn, _params) do
# User has not started an auth flow.
data = %{
2021-06-26 20:02:18 +00:00
flows: [%{stages: [@register_type]}],
params: %{}
}
conn
|> put_status(401)
|> json(data)
end
2021-06-26 20:02:18 +00:00
def login_types(conn, _params) do
data = %{flows: [%{type: @login_type}]}
2021-06-26 20:02:18 +00:00
conn
|> put_status(200)
|> json(data)
end
2021-06-27 15:28:28 +00:00
def login(
conn,
%{"type" => @login_type, "identifier" => %{"type" => "m.id.user"}} = params
) do
case Login.changeset(params) do
%Changeset{valid?: true} = cs ->
2021-07-17 15:38:20 +00:00
input = apply_changes(cs)
2021-06-27 15:28:28 +00:00
2021-07-17 15:38:20 +00:00
case Account.login(input) |> Repo.transaction() do
2021-06-27 15:28:28 +00:00
{:ok, device} ->
data = %{
2021-07-10 21:16:00 +00:00
user_id: MatrixServer.get_mxid(device.localpart),
2021-06-27 15:28:28 +00:00
access_token: device.access_token,
device_id: device.device_id
}
conn
|> put_status(200)
|> json(data)
{:error, error} ->
put_error(conn, error)
end
_ ->
put_error(conn, :bad_json)
end
end
def login(conn, _params) do
2021-06-27 15:28:28 +00:00
# Other login types and identifiers are unsupported for now.
put_error(conn, :unknown)
end
end