|
| 1 | +# |
| 2 | +# This file is part of Edgehog. |
| 3 | +# |
| 4 | +# Copyright 2026 SECO Mind Srl |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +# |
| 18 | +# SPDX-License-Identifier: Apache-2.0 |
| 19 | +# |
| 20 | + |
| 21 | +defmodule Edgehog.Auth.Changes.WriteTenant do |
| 22 | + @moduledoc """ |
| 23 | + Generic tuple writer. |
| 24 | + """ |
| 25 | + |
| 26 | + use Ash.Resource.Change |
| 27 | + |
| 28 | + alias Edgehog.Auth.FGAService |
| 29 | + |
| 30 | + require Logger |
| 31 | + |
| 32 | + @impl Ash.Resource.Change |
| 33 | + def init(opts) do |
| 34 | + errors = |
| 35 | + if Keyword.has_key?(opts, :obj), |
| 36 | + do: [], |
| 37 | + else: [:obj_missing] |
| 38 | + |
| 39 | + errors = |
| 40 | + if Keyword.has_key?(opts, :obj_id), |
| 41 | + do: errors, |
| 42 | + else: [:obj_id_missing | errors] |
| 43 | + |
| 44 | + if Enum.empty?(errors), |
| 45 | + do: {:ok, opts}, |
| 46 | + else: {:error, errors} |
| 47 | + end |
| 48 | + |
| 49 | + @impl Ash.Resource.Change |
| 50 | + def change(changeset, opts, context) do |
| 51 | + Ash.Changeset.after_transaction(changeset, &write_tenant_tuple(&1, &2, opts, context)) |
| 52 | + end |
| 53 | + |
| 54 | + defp write_tenant_tuple(_changeset, {:ok, result}, opts, %{tenant: tenant}) do |
| 55 | + # Writes the tuple |
| 56 | + # {"tenant:slug", "tenant", "obj:obj_id"} |
| 57 | + |
| 58 | + obj = opts[:obj] |> to_string() |
| 59 | + |
| 60 | + obj_id = opts[:obj_id] |
| 61 | + |
| 62 | + obj_id = |
| 63 | + result |
| 64 | + |> Ash.load!(obj_id) |
| 65 | + |> Map.get(obj_id) |
| 66 | + |> to_string() |
| 67 | + |
| 68 | + obj = "#{obj}:#{obj_id}" |
| 69 | + |
| 70 | + rel = "tenant" |
| 71 | + |
| 72 | + slug = tenant.slug |
| 73 | + subj = "tenant:#{slug}" |
| 74 | + |
| 75 | + with {:ok, _res} <- FGAService.write(subj, rel, obj) do |
| 76 | + {:ok, result} |
| 77 | + end |
| 78 | + end |
| 79 | + |
| 80 | + defp write_tenant_tuple(_changeset, error, opts, context) do |
| 81 | + Logger.debug("Error while executing DB transaction. Skipping writing tuple on the provider.", |
| 82 | + error: error, |
| 83 | + opts: opts, |
| 84 | + context: context |
| 85 | + ) |
| 86 | + |
| 87 | + error |
| 88 | + end |
| 89 | +end |
0 commit comments