architex/lib/architex_web/client/controllers/login_controller.ex

64 lines
1.6 KiB
Elixir
Raw Normal View History

2021-09-01 12:43:55 +00:00
defmodule ArchitexWeb.Client.LoginController do
use ArchitexWeb, :controller
2021-08-06 21:14:27 +00:00
2021-09-01 12:43:55 +00:00
import ArchitexWeb.Error
2021-08-06 21:14:27 +00:00
2021-09-01 12:43:55 +00:00
alias Architex.{Repo, Account, Device}
alias ArchitexWeb.Client.Request.Login
2021-08-06 21:14:27 +00:00
@login_type "m.login.password"
@doc """
Gets the homeserver's supported login types to authenticate users.
Action for GET /_matrix/client/r0/login.
"""
2021-08-06 21:14:27 +00:00
def login_types(conn, _params) do
data = %{flows: [%{type: @login_type}]}
conn
|> put_status(200)
|> json(data)
end
@doc """
Authenticates the user, and issues an access token they can use to
authorize themself in subsequent requests.
Action for POST /_matrix/client/r0/login.
"""
2021-08-06 21:14:27 +00:00
def login(
conn,
%{"type" => @login_type, "identifier" => %{"type" => "m.id.user"}} = params
) do
with {:ok, request} <- Login.parse(params) do
case Account.login(request) |> Repo.transaction() do
{:ok,
{%Account{localpart: localpart}, %Device{access_token: access_token, id: device_id}}} ->
data = %{
user_id: Architex.get_mxid(localpart),
access_token: access_token,
device_id: device_id
}
conn
|> put_status(200)
|> json(data)
{:error, error} when is_atom(error) ->
put_error(conn, error)
{:error, _} ->
put_error(conn, :unknown)
end
else
_ -> put_error(conn, :bad_json)
2021-08-06 21:14:27 +00:00
end
end
def login(conn, _params) do
# Other login types and identifiers are unsupported for now.
put_error(conn, :unrecognized, "Only m.login.password is supported currently.")
end
end