Implement register endpoint for m.login.dummy login type

Add device table
This commit is contained in:
Pim Kunis 2021-06-25 17:43:12 +02:00
parent 183120b5a1
commit d81a42bf8a
7 changed files with 229 additions and 19 deletions

View file

@ -1,7 +1,11 @@
defmodule MatrixServer.Account do
use Ecto.Schema
import MatrixServer
import Ecto.{Changeset, Query}
alias MatrixServer.{Repo, Account}
alias MatrixServer.{Repo, Account, Device}
alias Ecto.Multi
@max_mxid_length 255
@localpart_regex ~r/^([a-z0-9\._=\/])+$/
@ -9,7 +13,7 @@ defmodule MatrixServer.Account do
@primary_key {:localpart, :string, []}
schema "accounts" do
field :password_hash, :string, redact: true
has_many :devices, Device, foreign_key: :localpart
timestamps(updated_at: false)
end
@ -30,9 +34,19 @@ defmodule MatrixServer.Account do
end
end
def changeset(%Account{} = account, attrs) do
def register(params) do
Multi.new()
|> Multi.insert(:account, changeset(%Account{}, params))
|> Multi.insert(:device, fn %{account: account} ->
Ecto.build_assoc(account, :devices)
|> Device.changeset(params)
end)
|> Multi.run(:device_with_access_token, &Device.generate_access_token/2)
end
def changeset(account, params \\ %{}) do
account
|> cast(attrs, [:localpart, :password_hash])
|> cast(params, [:localpart, :password_hash])
|> validate_required([:localpart, :password_hash])
|> validate_length(:password_hash, max: 60)
|> validate_format(:localpart, @localpart_regex)
@ -44,8 +58,4 @@ defmodule MatrixServer.Account do
# Subtract the "@" and ":" in the MXID.
@max_mxid_length - 2 - String.length(server_name())
end
defp server_name do
Application.get_env(:matrix_server, :server_name)
end
end

View file

@ -0,0 +1,32 @@
defmodule MatrixServer.Device do
use Ecto.Schema
import Ecto.Changeset
alias MatrixServer.{Account, Device}
@primary_key false
schema "devices" do
field :device_id, :string, primary_key: true
field :access_token, :string
field :display_name, :string
belongs_to :account, Account,
foreign_key: :localpart,
references: :localpart,
type: :string,
primary_key: true
end
def changeset(device, params \\ %{}) do
device
|> cast(params, [:localpart, :device_id, :access_token, :display_name])
|> validate_required([:localpart, :device_id])
|> unique_constraint([:localpart, :device_id], name: :devices_pkey)
end
def generate_access_token(repo, %{device: %Device{localpart: localpart, device_id: device_id} = device}) do
access_token = Phoenix.Token.encrypt(MatrixServerWeb.Endpoint, "access_token", {localpart, device_id})
device
|> change(%{access_token: access_token})
|> repo.update()
end
end