architex/lib/architex_web/federation/controllers/query_controller.ex

62 lines
1.6 KiB
Elixir
Raw Normal View History

2021-09-01 12:43:55 +00:00
defmodule ArchitexWeb.Federation.QueryController do
use ArchitexWeb, :controller
use ArchitexWeb.Federation.AuthenticateServer
2021-08-10 16:02:53 +00:00
2021-09-01 12:43:55 +00:00
import ArchitexWeb.Error
2021-08-10 16:02:53 +00:00
import Ecto.Query
2021-09-01 12:43:55 +00:00
alias Architex.{Repo, Account}
alias Architex.Types.UserId
2021-08-10 16:02:53 +00:00
defmodule ProfileRequest do
use Ecto.Schema
import Ecto.Changeset
@primary_key false
embedded_schema do
field :user_id, UserId
2021-08-10 16:02:53 +00:00
field :field, :string
end
def validate(params) do
%__MODULE__{}
|> cast(params, [:user_id, :field])
|> validate_required([:user_id])
|> validate_inclusion(:field, ["displayname", "avatar_url"])
|> then(fn
2021-08-10 16:02:53 +00:00
%Ecto.Changeset{valid?: true} = cs -> {:ok, apply_changes(cs)}
_ -> :error
end)
end
end
@doc """
Performs a query to get profile information, such as a display name or avatar,
for a given user.
Action for GET /_matrix/federation/v1/query/profile.
"""
2021-08-10 16:02:53 +00:00
def profile(conn, params) do
with {:ok, %ProfileRequest{user_id: %UserId{localpart: localpart, domain: domain}}} <-
ProfileRequest.validate(params) do
2021-09-01 12:43:55 +00:00
if domain == Architex.server_name() do
2021-08-10 16:02:53 +00:00
case Repo.one(from a in Account, where: a.localpart == ^localpart) do
%Account{} ->
# TODO: Return displayname and avatar_url when we implement them.
conn
|> put_status(200)
|> json(%{})
nil ->
put_error(conn, :not_found, "User does not exist.")
2021-08-10 16:02:53 +00:00
end
else
put_error(conn, :not_found, "Wrong server name.")
2021-08-10 16:02:53 +00:00
end
else
_ -> put_error(conn, :bad_json)
end
end
end