2021-05-06 12:27:04 +02:00
|
|
|
defmodule Mobilizon.Users.PushSubscription do
|
|
|
|
use Ecto.Schema
|
|
|
|
alias Mobilizon.Users.User
|
|
|
|
import Ecto.Changeset
|
|
|
|
|
2021-05-06 18:39:59 +02:00
|
|
|
@primary_key {:id, :binary_id, autogenerate: true}
|
2021-05-06 12:27:04 +02:00
|
|
|
schema "user_push_subscriptions" do
|
|
|
|
field(:digest, :string)
|
|
|
|
belongs_to(:user, User)
|
2021-05-06 18:39:59 +02:00
|
|
|
field(:endpoint, :string)
|
|
|
|
field(:auth, :string)
|
|
|
|
field(:p256dh, :string)
|
2021-05-06 12:27:04 +02:00
|
|
|
timestamps()
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
def changeset(push_subscription, attrs) do
|
|
|
|
push_subscription
|
2021-05-06 18:39:59 +02:00
|
|
|
|> cast(attrs, [:user_id, :endpoint, :auth, :p256dh])
|
|
|
|
|> put_change(:digest, compute_digest(attrs))
|
|
|
|
|> validate_required([:digest, :user_id, :endpoint, :auth, :p256dh])
|
|
|
|
|> unique_constraint([:digest, :user_id], name: :user_push_subscriptions_user_id_digest_index)
|
2021-05-06 12:27:04 +02:00
|
|
|
end
|
|
|
|
|
2021-05-06 18:39:59 +02:00
|
|
|
defp compute_digest(attrs) do
|
|
|
|
data =
|
|
|
|
Jason.encode!(%{endpoint: attrs.endpoint, keys: %{auth: attrs.auth, p256dh: attrs.p256dh}})
|
2021-05-06 12:27:04 +02:00
|
|
|
|
|
|
|
:sha256
|
|
|
|
|> :crypto.hash(data)
|
|
|
|
|> Base.encode16()
|
|
|
|
end
|
|
|
|
end
|