2021-05-06 12:27:04 +02:00
|
|
|
defmodule Mobilizon.Users.PushSubscription do
|
2021-06-03 15:00:49 +02:00
|
|
|
@moduledoc """
|
|
|
|
Represents informations about a push subscription for a specific user
|
|
|
|
"""
|
2021-05-06 12:27:04 +02:00
|
|
|
use Ecto.Schema
|
|
|
|
alias Mobilizon.Users.User
|
|
|
|
import Ecto.Changeset
|
|
|
|
|
2021-09-10 11:36:05 +02:00
|
|
|
@type t :: %__MODULE__{
|
|
|
|
digest: String.t(),
|
|
|
|
user: User.t(),
|
|
|
|
endpoint: String.t(),
|
|
|
|
auth: String.t(),
|
|
|
|
p256dh: String.t()
|
|
|
|
}
|
|
|
|
|
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
|
2021-09-24 16:46:42 +02:00
|
|
|
@spec changeset(t | Ecto.Schema.t(), map) :: Ecto.Changeset.t()
|
2021-05-06 12:27:04 +02:00
|
|
|
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-10-04 18:59:41 +02:00
|
|
|
@spec compute_digest(map()) :: String.t()
|
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
|