Merge branch 'feature/521-pinned-post-federation' into 'develop'
[akkoma] / lib / pleroma / registration.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Registration do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9
10 alias Pleroma.Registration
11 alias Pleroma.Repo
12 alias Pleroma.User
13
14 @primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
15
16 schema "registrations" do
17 belongs_to(:user, User, type: FlakeId.Ecto.CompatType)
18 field(:provider, :string)
19 field(:uid, :string)
20 field(:info, :map, default: %{})
21
22 timestamps()
23 end
24
25 def nickname(registration, default \\ nil),
26 do: Map.get(registration.info, "nickname", default)
27
28 def email(registration, default \\ nil),
29 do: Map.get(registration.info, "email", default)
30
31 def name(registration, default \\ nil),
32 do: Map.get(registration.info, "name", default)
33
34 def description(registration, default \\ nil),
35 do: Map.get(registration.info, "description", default)
36
37 def changeset(registration, params \\ %{}) do
38 registration
39 |> cast(params, [:user_id, :provider, :uid, :info])
40 |> validate_required([:provider, :uid])
41 |> foreign_key_constraint(:user_id)
42 |> unique_constraint(:uid, name: :registrations_provider_uid_index)
43 end
44
45 def bind_to_user(registration, user) do
46 registration
47 |> changeset(%{user_id: (user && user.id) || nil})
48 |> Repo.update()
49 end
50
51 def get_by_provider_uid(provider, uid) do
52 Repo.get_by(Registration,
53 provider: to_string(provider),
54 uid: to_string(uid)
55 )
56 end
57 end